多台初始状态虚拟机,已分配IP地址。需要批量分发ssh公钥,使用管理机m01
进行连接,且避免首次连接提示。
首先本机的/etc/hosts
文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 192.168.110.144 lb401 192.168.110.145 lb402 192.168.110.135 lb01 192.168.110.136 lb02 192.168.110.137 web01 192.168.110.138 web02 192.168.110.139 sweb01 192.168.110.140 sweb02 192.168.110.141 nfs 192.168.110.142 backup 192.168.110.143 db01 192.168.110.128 m01
|
创建一个包含所有远程主机hostname的文件/root/ip.txt
1 2 3 4 5 6 7 8 9 10 11
| 192.168.110.144 lb401 192.168.110.145 lb402 192.168.110.135 lb01 192.168.110.136 lb02 192.168.110.137 web01 192.168.110.138 web02 192.168.110.139 sweb01 192.168.110.140 sweb02 192.168.110.141 nfs 192.168.110.142 backup 192.168.110.143 db01
|
本机编辑批量分发ssh公钥的脚本/server/script/distribute_ssh_key.sh
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #!/usr/bin/env bash
set -e [ -f /root/.ssh/id_rsa ] || ssh-keygen -t rsa -f /root/.ssh/id_rsa -P "" &>/dev/null [ -f /usr/bin/sshpass ] || yum -y install sshpass &> /dev/null while read line do host=`echo $line | cut -d " " -f2` echo "=============host $ip pub-key start distribute=============" sshpass -p '123456' ssh-copy-id -i /root/.ssh/id_rsa.pub dengpangpang@${host} -o "StrictHostKeyChecking=no" &> /dev/null ssh-keyscan -H ${host} >> ~/.ssh/known_hosts echo "host $host distribute success." echo "=============host $host pub-key distribute end=============" echo "" done < /root/ip.txt
|
1 2 3
|
sshpass -p '123456' ssh-copy-id -i /root/.ssh/id_rsa.pub dengpangpang@${host} -o "StrictHostKeyChecking=no" &> /dev/null
|
1 2
| ssh-keyscan -H ${host} >> ~/.ssh/known_hosts
|
执行这条脚本之后,所有的主机都添加了管理机的公钥,并且管理机的known_hosts
文件保存了所有远程主机的公钥信息,这样连接时无需首次确认。
测试:
1
| ansible all -u dengpangpang -m ping
|
测试结果:全绿。