1. 使用脚本配合实现单个分发

新建一个expect脚本文件,内如如下:
#!/usr/bin/expect
if { $argc != 2 } {
send_user “usage: expect fenfa_sshkey.exp file host\n”
exit
}

define var
set file [lindex $argv 0]
set host [lindex $argv 1]
set password “123456”

spawn ssh-copy-id -i $file “-p 65533 oldboy888@$host”
expect {
“yes/no” {send “yes\r”;exp_continue}
“*password” {send “$password\r”}
}
expect eof

exit -noexit {
send_user “Oldboy888 say good bye to your!\n”
}

这个脚本需要接收两个参数,一个是文件地址,一个是主机IP地址。
使用例子如下:

expect fenfa_sshkey.exp .ssh/id_dsa.pub 172.16.1.31
结果:
使用expect脚本批量分发密钥 - 图1

2. 使用脚本配合实现批量分发

!/bin/sh
. /etc/init.d/functions
for ip in 8 41 31
do
expect fenfa_sshkey.exp ~/.ssh/id_dsa.pub 172.16.1.$ip >/dev/null 2>&1

if [ $? -eq 0 ];then
action “$ip” /bin/true
else
action “$ip” /bin/false
fi
done
这样直接运行此脚本即可实现批量分发密钥。
运行结果截图:
使用expect脚本批量分发密钥 - 图2