借助sshpass+ssh或者使用expect实现交互式密码登陆或密钥推送
具体方法
方法一 sshpass+ssh
首先需要安装sshpass(系统中默认没有这个命令,安装过程不再描述)
向远程主机传送文件后将公钥导入到目标主机的authorited_keys文件内
点击(此处)折叠或打开
- Usage: sshpass [-f|-d|-p|-e] [-hV] command parameters
-
-f filename Take password to use from file
-
-d number Use number as file descriptor for getting password
-
-p password Provide password as argument (security unwise)
-
-e Password is passed as env-var "SSHPASS"
-
With no parameters - password will be taken from stdin
-
-
-h Show help (this screen)
-
-V Print version information
- At most one of -f, -d, -p or -e should be used
点击(此处)折叠或打开
- #!/bin/bash
- #this script is to send pub key to romote host
- #authors:
- #date:
- for remote_ip in `cat IP.txt`
- do
- echo "###################"
- sshpass -p "yourpasswd" scp -o StrictHostKeyChecking=no ~/.ssh/id_rsa.pub remote_user@${remote_ip}:/path
- ssh remote_user@remote_ip <<-eof
- cat /path/id_rsa.pub >>/home/remote_user/.ssh/authorized_keys
- rm -f /path/id_rsa.pub
- eof
- #或者ssh remote_user@remote_ip "cat /path/id_rsa.pub >>/home/remote_user/.ssh/authorized_keys;rm -f /path/id_rsa.pub"
- done
只需提前将需要推送公钥的主机IP地址写到同一个文件内,这里为IP.txt,然后执行该脚本即可。
-o StrictHostKeyChecking=no
对于ssh的第一次登陆,会提示:
“Are you sure you want to continue connecting (yes/no)”,这时用sshpass会不好使,可以在执行的命令后面添加
-o StrictHostKeyChecking=no 来解决。
由于ssh-copy-id 不支持该选项我们的实现方式为先将id_pub.sh利用scp推送到远程主机,后执行远程命令将内容导入到认证文件authoritied_keys,取得和ssh-copy-id的效果,最后再删除传送的文件即可。
如果需要ssh到目标机器上sudo执行命令,可以使用ssh -t
方法二 利用expect