expect结合shell批量免密配置脚本

1. 先在本机安装expect命令

 yum -y install expect

2. 在需要配置免密登录的主机上做ssh服务优化

在本实验中需要做免密登录的主机ip为:

192.168.153.136 
192.168.153.137

优化设置
链接>> https://blog.csdn.net/m0_46674735/article/details/112168847?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522161036223716780258084964%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fblog.%2522%257D&request_id=161036223716780258084964&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2blogfirst_rank_v1~rank_blog_v1-11-112168847.pc_v1_rank_blog_v1&utm_term=ssh&spm=1018.2226.3001.4450

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

猜你喜欢

转载自blog.csdn.net/m0_46674735/article/details/112465063
今日推荐