用spawn 实现ssh-copy-id 免密码自动化
安装依赖软件
yum install -y tcl tclx tcl-devel
yum -y install expect
编写脚本
vim ssh-copy-id.sh
#!/usr/bin/expect
set timeout 10
set username [lindex $argv 0]
set password [lindex $argv 1]
set hostname [lindex $argv 2]
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $username@$hostname
expect {
#first connect, no public key in ~/.ssh/known_hosts
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
expect "password:"
send "$password\r"
}
#already has public key in ~/.ssh/known_hosts
"password:" {
send "$password\r"
}
"Now try logging into the machine" {
#it has authorized, do nothing!
}
}
expect eof
运行脚本
expect -f /fjyl/Script/ssh-copy-id.sh root 123456 192.168.1.100
此方法在CentOS Linux release 7.4.1708 (Core) 测试过没问题。