自动化运维工具ansible需要基于ssh key验证免密登录。
#!/bin/bash # #======================================================================== # # author: 9528 # mail: scsc4212@163.com # date: 2019-7-24 # #------------------------------------------------------------------------ # 简述: # 脚本实现批量推送公钥,实现ssh key验证免密登陆,ip地址由ip.txt文件 # 导入,success_ip.txt存放推送成功的ip地址,failed_ip.txt存放推送失败的ip # 地址。 # # 待改进: # 明文存放密码风险 # #======================================================================== # . /etc/init.d/functions #被推送主机的密码 password="7654321" #创建文件,存放推送成功的ip >success_ip.txt #创建文件,存放推送失败的ip >failed_ip.txt # #检查是否按照了expect软件包 # rpm -q expect &>/dev/null || (echo "------start install expect!------" && yum install expect -y &> /dev/null) if [ $? -ne 0 ] then echo -e "\033[31m------install expect failed!------\033[0m" echo -e "\033[31m------end exit!------\033[0m" exit 2 fi # #检查本机密钥是否丢失,若丢失则重新生成密钥 # if [ ! -f ~/.ssh/id_rsa ] || [ ! -f ~/.ssh/id_rsa.pub ] then rm -f ~/.ssh/id_rsa* echo "------start ssh-keygen!------" ssh-keygen -P "" -f ~/.ssh/id_rsa &> /dev/null if [ $? -ne 0 ] then echo -e "\033[31m------ssh-keygen failed!------\033[0m" echo -e "\033[31m------end exit!------\033[0m" exit 2 fi fi # #检查ip是否能ping通,能ping通才推送秘钥 # echo "------start ssh-copy-id!------" while read ip do ping -c1 -W3 $ip &> /dev/null if [ $? -eq 0 ] then expect &> key.log <<- EOF spawn ssh-copy-id $ip set timeout 10 expect { "yes/no" { send "yes\r"; exp_continue} "password" { send "$password\r" } } expect eof EOF sleep 0.5 # #通过每次执行后的信息区分下面三种情况: # 1.正常推送成功 # 2.原来的密钥已推送过,这种情况我们也标记成推送成功 # 3.password验证错误导致推送失败 # if fgrep -q "try logging into the machine" key.log then echo $ip >> success_ip.txt action "$ip" /bin/true elif fgrep -q "they already exist on the remote system." key.log then echo $ip >> success_ip.txt action "$ip" /bin/true else fgrep -q "Permission denied, please try again." key.log echo $ip >> failed_ip.txt action "$ip" /bin/false fi # #ping不通的情况 # else action "$ip" /bin/false echo $ip >> failed_ip.txt fi done < ip.txt echo -e "\n\033[34m------------finish!------------\033[0m\n"执行结果
[root@localhost ~]$bash key.sh ------start install expect!------ ------start ssh-keygen!------ ------start ssh-copy-id!------ 192.168.1.77 [ OK ] 192.168.1.88 [ OK ] ------------finish!------------相关文件
[root@localhost ~]$ls *txt failed_ip.txt ip.txt success_ip.txt
