使用expect向ip列表文件中的ip主机,执行ssh-copy-id命令复制密钥,以实现ssh免密登陆。
安装expect
yum install -y expect
生成密钥对
ssh-keygen -t rsa -P '' -f ~/.ssh/id_rsa
脚本
//shell脚本内容
# -------------------------
vim ssh-copy-id.sh
#!/bin/bash
#
[ $# -gt 0 -a -f "$1" ] || exit 1
cat $1 | while read ip ;do
user='root'
password='centos'
expect ./ssh-copy-id.exp $ip $user $password
done
//expect脚本内容
-------------------------
vim ssh-copy-id.exp
#!/usr/bin/expect
set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]
set timeout 10
spawn ssh-copy-id $user@$ip
expect {
"yes/no" { send "yes
";exp_continue }
"password" { send "$password
" }
}
expect eof
//iplists文件
-------------------------
vim iplists.txt
192.168.10.101
192.168.10.102
192.168.10.103
192.168.10.104
192.168.10.105
//调用脚本
sh ssh-copy-id.sh iplists.txt