转载自 https://www.mr-mao.cn/archives/auto-configure-ssh-nopass-login.html
1、在主机的操作系统上安装expect
2、新建host_ip文件,内容格式如下
host_ip文件格式
172.16.1.100 password
172.16.1.101 password
172.16.1.102 password
172.16.1.103 password
172.16.1.104 password
172.16.1.105 password
172.16.1.106 password
172.16.1.107 password
172.16.1.108 password
.....
脚本代码
#!/bin/bash
#定义批量IP和密码 for循环执行批量命令
for row in `cat host_ip | awk '{printf("%s:%s:%s\n"),$1,$2,$3}'`
do
ip=`echo ${row} | awk -F ':' '{print $1}'`
password=`echo ${row} | awk -F ':' '{print $2}'`
#在列出的所有的主机上生成密钥对
/usr/bin/expect <<-EOF
spawn ssh root@$ip ssh-keygen -t rsa
expect {
"yes/no" {send "yes\r";exp_continue}
"password: " {send "$password\r";exp_continue}
"/root/.ssh/id_rsa" {send "\r";exp_continue}
"empty for no passphrase" {send "\r";exp_continue}
"again" {send "\r";exp_continue}
}
exit
EOF
#如果只是管理机无密登录,使用此步
#/usr/bin/expect <<-EOF
#spawn ssh-copy-id -i /root/.ssh/id_rsa.pub $ip
#expect {
# "yes/no" {send "yes\r";exp_continue}
# "password: " {send "$password\r";exp_continue}
# }
#EOF
#把列出的所有的主机的公钥复制到本地
/usr/bin/expect <<-EOF
spawn scp root@$ip:/root/.ssh/id_rsa.pub /root/.ssh/id_rsa.pub_$ip
expect {
"yes/no" {send "yes\r";exp_continue}
"password: " {send "$password\r";exp_continue}
}
EOF
done
#如果只是管理机无密登录,使用此步
#localip=`ip a s |grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"|grep -o '[0-9]\+\.[0-9]\+\.[0-9]\+\.[0-9]\+'`
#rm -rf ~/.ssh/id_rsa.pub_$localip
#把所有主机的公钥拷贝到密钥key
cat /root/.ssh/id_rsa.pub_* >> /root/.ssh/authorized_keys
for row in `cat host_ip | awk '{printf("%s:%s:%s\n"),$1,$2,$3}'`
do
ip=`echo ${row} | awk -F ':' '{print $1}'`
password=`echo ${row} | awk -F ':' '{print $2}'`
#把含有所有主机公钥的密钥key复制到所有的主机
/usr/bin/expect <<-EOF
spawn scp /root/.ssh/authorized_keys root@$ip:/root/.ssh/
expect {
"yes/no" { send "yes\r";exp_continue}
"password: " {send "$password\r";exp_continue}
}
EOF
#复制hosts文件到所有主机
/usr/bin/expect <<-EOF
spawn scp /etc/hosts root@$ip:/etc/
expect {
"yes/no" { send "yes\r";exp_continue}
"password: " {send "$password\r";exp_continue}
}
EOF
done