有时侯,操作 ssh 在当地执行长途呆板的呼吁可以便捷地处理惩罚某些反复事情。我们但愿做到:
免手工输入暗码
我们可以利用 ssh 互信,昆山软件开发,sshpass 和 expect 等东西来制止手工输暗码。利用进程大概会遇到如下需要手工输入 yes 的繁琐场景:
$ ssh username@hostname The authenticity of host ... can't be established. ECDSA key fingerprint is ... Are you sure you want to continue connecting (yes/no)?
为了制止呈现上述场景,往 ssh 呼吁添加如下参数:
$ ssh -o "StrictHostKeyChecking no" username@password
SSH 互信
SSH 互信的设置很是简朴,首先生成 ssh key:
$ ssh-keygen
把 public key 拷贝到信任方中:
$ ssh-copy-id -i ~/.ssh/id_rsa.pub username@hostname
之后免密执行呼吁:
$ ssh -o "StrictHostKeyChecking no" username@password cmd
sshpass
sshpass 是一个用于非交互的 ssh 暗码验证东西,利用前先安装:
$ yum install sshpass
利用如下:
$ sshpass -p password ssh -o "StrictHostKeyChecking no" username@hostname cmd
expect
Expect 是用来举办自动化节制和测试的软件东西。固然进修本钱较高,可是 expect 的成果强大,操作 expect 可以利便的执行长途呼吁。利用前先安装:
$ yum install expect
譬喻:
#!/usr/bin/expect spawn ssh -o "StrictHostKeyChecking no" username@hostname expect "*assword*" send "password\n" expect "*$*" send "command\n" expect "*$*" send "exit\n" expect eof
Expect 不只支持 ssh,还支持 scp, ftp 等东西。
支持多呼吁和剧本
执行多条呼吁
sshpass 和 expect 在支持多条呼吁上很是雷同,昆山软件开发,只需用 && 毗连呼吁即可:
# ssh trust $ ssh -o "StrictHostKeyChecking no" username@password "cmd1 && cmd2"
譬喻:
# sshpass $ sshpass -p password ssh -o "StrictHostKeyChecking no" username@password "ls -a && mkdir test" # expect ...... expect "*$*" send "ls -a && mkdir test\n" ......
执行当地剧本
对付执行当地剧本,ssh 和 sshpass 的用法雷同。
# ssh trust $ ssh -o "StrictHostKeyChecking no" username@password bash -s < shell_script.sh # sshpass $ sshpass -p password ssh -o "StrictHostKeyChecking no" username@password bash -s < shell_script.sh
对付 expect,首先需要把剧本拷贝到长途主机,然后在长途主机执行该剧本,昆山软件开发,步调如下:
... # Copy script to remote host spawn scp -o "StrictHostKeyChecking no" shell_script.sh username@hostname:~/ expect "*assword*" send "password\n" expect "*100%*" expect eof # Execute the shell script at remote host spawn ssh -o "StrictHostKeyChecking no" username@hostname expect "*assword*" send "password\n" expect "*$*" send "sh shell_script.sh\n" ......
支持执行 sudo 呼吁
有些呼吁需要 sudo 权限才气执行,可是我们不但愿反复的输入暗码,我们可以把每条呼吁修改为如下:
cmd ---> 'echo password | sudo -S cmd'
譬喻:
sshpass -p password ssh -o "StrictHostKeyChecking no" username@password "echo password | sudo -S mkdir /newdir"
对付如 echo, dd 等部门呼吁,有时会呈现如下失败场景:
$ sshpass -p password ssh -o "StrictHostKeyChecking no" username@password 'echo password | sudo -S echo hello > /newdir/newfile' bash: /newdir/newfile: 权限不足
办理步伐如下:
cmd ---> 'echo password | sudo -S sh -c "cmd"' # For example $ sshpass -p password ssh -o "StrictHostKeyChecking no" username@password 'echo WSfdl097018= | sudo -S sh -c "echo hello > /newdir/newfile"'