首先在服务器上生成密钥,ssh-keygen -t rsa,输入密码等,或留空,例如生成了/root/.ssh/id_rsa_cenosb.pub文件
将要SSH远程连接的所有主机的IP,用户名,密码写在同一目录的pwd.txt,以空格作为分隔符,搞定以后可以删除
脚本如下
#!/bin/bash
a=`cat /root/.ssh/id_rsa_cenosb.pub`
cat pwd.txt | while read line
do
hostip=`echo $line | cut -d" " -f1`
uname=`echo $line | cut -d" " -f2`
pwd=`echo $line | cut -d" " -f3`
/usr/bin/expect <<-EOF
set time 30
spawn ssh $uname@$hostip
expect {
"*yes/no" { send "yes\r"; exp_continue }
"*password:" { send "$pwd\r" }
}
expect "*#"
send "echo $a >> /root/.ssh/authorized_keys\r"
expect "*#"
send "exit\r"
interact
expect eof
EOF
#echo "$pwd"
done