使用Spawn和expect实现ssh自动登陆
- ubuntu 系统
sudo apt-get install tcl tk expect
- centos 系统
yum install expect
- /tmp/ssh-copy-id.sh
⚠️ spawn 命令只有在expect 环境下才有
#!/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
- 执行ssh-copy-id 实现无密码登陆
sshUser="ubuntu"
password="Admin123456"
publicIp="40.83.121.212"
expect -f /fjyl/Script/ssh-copy-id.sh ${sshUser} ${password} ${publicIp}
执行结果:
[root@jenkins-slave~]# expect -f /tmp/ssh-copy-id.sh ubuntu Admin123456 40.83.121.212
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub ubuntu@40.83.121.212
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
ubuntu@40.83.121.212's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'ubuntu@40.83.121.212'"
and check to make sure that only the key(s) you wanted were added.
现在只要执行 ssh ubuntu@40.83.121.212 就可以进入系统了。