方法1:
#!/bin/bash
#
#********************************************************************
#Author: Razor
#QQ: 254456122
#Date: 2021-10-29
#FileName sshkey.sh
#URL: https://blog.csdn.net/mandarin_meng?spm=1019.2139.3001.5343
#Description The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
COLOR="echo -e \E[1;32m"
END="\E[0m"
PASSWORD=123456
IPLIST="
192.168.8.8
192.168.8.21
"
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -P "" -f ~/.ssh/id_rsa &>/dev/null
rpm -q expect &> /dev/null || yum -y -q install expect &>/dev/null
for ip in $IPLIST ;do
{
expect <<EOF
set timeout 60
spawn ssh-copy-id $ip
expect {
"yes/no" { send "yes\r";exp_continue }
"password:" { send "$PASSWORD\r" }
}
expect eof
EOF
$COLOR"$ip is ready"$END
}&
done
wait
$COLOR"Push ssh key is finished!"$END
范例:基于key验证实现批量主机管理
[root@cent8 data]#cat host.txt
192.168.8.8
192.168.8.21
[root@cent8 data]#for i in `cat host.txt`;do ssh $i hostname -I ;done
192.168.8.8
192.168.8.21
方法2:
或者将远程需要推送的主机列表放到一个文件中,这样以后就不需要每次都修改脚本了
#!/bin/bash
#
#********************************************************************
#Author: Razor
#QQ: 254456122
#Date: 2021-10-29
#FileName sshkey1.sh
#URL: https://blog.csdn.net/mandarin_meng?spm=1019.2139.3001.5343
#Description The test script
#Copyright (C): 2021 All rights reserved
#********************************************************************
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
PASS=123456
rpm -q expect &> /dev/null || yum -y install expect &> /dev/null
[ ! -f ~/.ssh/id_rsa ] && ssh-keygen -t rsa -P "" -f /root/.ssh/id_rsa &> /dev/null && echo "ssh key is created"
while read IP ;do
expect <<EOF &> /dev/null
set timeout 20
spawn ssh-copy-id -i /root/.ssh/id_rsa.pub root@$IP
expect {
"yes/no" { send "yes\r";exp_continue }
"password" { send "$PASS\r" }
}
expect eof
EOF
echo $IP is ready
done < hosts.txt
[root@cent8 data]#cat hosts.txt
192.168.8.8
192.168.8.21
[root@cent8 data]#