【Shell】通过shell脚本批量部署ssh私钥认证

admin / Shell / / 311 字 · 约 7 分钟 / 591 次阅读 /

通过 shell 脚本批量部署 ssh 私钥认证

批量管理服务器是个力气活,如果手动一台一台去搞,会很费劲。所有就会有 saltstack,ansible,puppet 这些批量管理工具

普通方法实现 ssh 免密登录

在登录机上生成公钥和私钥

$ ssh-keygen -t ras # 一路回车,在/root下生成一个.ssh的目录,这个目录里有id_rsa.pub(公钥文件),id_rsa(私钥文件)

把公钥拷贝到远程服务端

$ ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.1 # 输入密码
$ ssh 192.168.1.1 # 就会发现就不用再输密码了

批量部署 ssh 私钥的认证脚本

主脚本

首先要查看是否有 expect 这个命令,可以用 which expect 来确定是否有这个命令,没有的话 yum 安装即可

$ yum install expect
$ cat /root/batch_sshkey.sh
#!/bin/bash
cd /root
cat /root/.ssh/id_rsa.pub > /root/.ssh/authorized_keys
for i in `cat ip.txt`
do
ip=$(echo "$i"|cut -f1 -d":")
password=$(echo "$i"|cut -f2 -d":")

expect -c "
spawn scp /root/.ssh/authorized_keys /root/remote_operate.sh  root@$ip:/tmp/
        expect {
                \"*yes/no*\" {send \"yes\r\"; exp_continue}
                \"*password*\" {send \"$password\r\"; exp_continue}
                \"*Password*\" {send \"$password\r\";}
        }
"
expect -c "
spawn ssh root@$ip "/tmp/remote_operate.sh"
        expect {
                \"*yes/no*\" {send \"yes\r\"; exp_continue}
                \"*password*\" {send \"$password\r\"; exp_continue}
                \"*Password*\" {send \"$password\r\";}
        }
"
done
$ chmod +x /root/batch_sshkey.sh

建立被登录端的 IP 列表

列表中服务器 IP 和密码用冒号":" 分割

$ cat ip.txt
192.168.1.1:admin1
192.168.8.220:admin2

建立 remote_operate.sh

这个脚本用来查看服务器端的.ssh 文件是否存在,同时将私钥拷贝到该目录下

$ cat remote_operate.sh
#!/bin/bash
if [ ! -d /root/.ssh ];then
mkdir /root/.ssh
fi
cat /tmp/authorized_keys > /root/.ssh/authorized_keys
rm -rf /tmp/authorized_keys /tmp/remote_operate.sh

执行脚本测试

$ ./batch_sshkey.ssh
spawn scp /root/.ssh/authorized_keys /root/remote_operate.sh root@192.168.1.1:/tmp/
authorized_keys                                                                                                                                                              100%  396     0.4KB/s   00:00
remote_operate.sh                                                                                                                                                            100%  170     0.2KB/s   00:00
spawn ssh root@192.168.8.220 /tmp/remote_operate.sh
spawn scp /root/.ssh/authorized_keys /root/remote_operate.sh root@192.168.8.220:/tmp/
authorized_keys                                                                                                                                                              100%  396     0.4KB/s   00:00
remote_operate.sh                                                                                                                                                            100%  170     0.2KB/s   00:00
spawn ssh root@192.168.66.13 /tmp/remote_operate.sh
$ ssh 192.168.1.1 # 测试是否能免密登录
$ ssh 192.168.8.220 # 测试是否能免密登录
admin

admin

云原生架构 · 全栈开发

感谢阅读本文!记录系统架构思考与实战复盘。专注于 Python、Django、PostgreSQL 与云原生容器化工程实践。