1. 先在本机安装expect命令
yum -y install expect
2. 在需要配置免密登录的主机上做ssh服务优化
在本实验中需要做免密登录的主机ip为:
192.168.153.136
192.168.153.137
2. 编写脚本内容如下:
#!/bin/bash
#将要配置主机的ip定义为数组
IP=(192.168.153.136 192.168.153.137)
#判断本机的公钥是否生成
if [ ! -f /root/.ssh/id_rsa.pub ];then
expect << EOF
spawn ssh-keygen
expect "ssh/id_rsa):" {send "\r"}
expect "passphrase):" {send "\r"}
expect "again:" {send "\r"}
expect eof
EOF
fi
#发送公钥到远程主机
for i in ${IP[*]}
do
expect << EOF
spawn ssh-copy-id root@$i
expect {
"(yes/no)" {send "yes\r";exp_continue}
"password:" {send "jundong\r"}
}
expect eof
EOF
done
3. 给脚本增加执行权限
chmod +x plssh.sh
4. 执行脚本
[root@host-135 ~]# sh plssh.sh
spawn ssh-copy-id root@192.168.153.136
/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
root@192.168.153.136's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
spawn ssh-copy-id root@192.168.153.137
/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
root@192.168.153.137's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
5. 验证实验效果
[root@host-135 ~]# ssh [email protected]
Last login: Wed Jan 6 09:15:41 2021 from 192.168.153.1
[root@host-136 ~]# exit
logout
Connection to 192.168.153.136 closed.
[root@host-135 ~]# ssh [email protected]
Last login: Mon Jan 11 10:49:29 2021 from 192.168.153.1
[root@host-137 ~]# exit
logout