1、vim ssh_key.sh ##脚本
#!/bin/bash
function auth_key () {
/usr/bin/expect <<EOF
spawn ssh-copy-id -i /root/.ssh/id_dsa.pub $username@$hostname
expect {
#first connect, no public key in ~/.ssh/known_hosts
"Are you sure you want to continue connecting (yes/no)?" {
send "yes\r"
expect "password:"
send "$password\r"
}
#already has public key in ~/.ssh/known_hosts
"password:" {
send "$password\r"
}
"Now try logging into the machine" {
#it has authorized, do nothing!
}
}
expect eof
EOF
}
function no () {
/usr/bin/ssh-keygen -t dsa -P '' -f ~/.ssh/id_dsa
}
function yes () {
username="root"
password="123456"
#read -p "Please enter the password free login to SSH IP addres :" ip
ip=`cat /opt/ip.txt` #如果ip比较多,取消本行注释,吧所有ip地址,成列放到ip.txt文件中,并注释掉read上一行
for hostname in $ip
do
auth_key $username $password $hostname
done
}
if [ ! -e "/usr/bin/expect" ]
then
/usr/bin/yum -y install expect >/dev/null
fi
file=/root/.ssh/id_*.pub
if [ -f $file ]
then
yes >/dev/null
echo "ssh-keygen success !"
else
no >/dev/null
yes >/dev/null
echo "ssh-keygen success !"
fi
2、执行脚本(输入要做免秘钥登录的ip地址)
[root@hhhh opt]# sh ssh_key.sh
Generating public/private dsa key pair.
Your identification has been saved in /root/.ssh/id_dsa.
Your public key has been saved in /root/.ssh/id_dsa.pub.
The key fingerprint is:
SHA256:19kk2B2qFPyB+L5+huCIScv5UTuxSY/A2lmEBBE3geE root@hhhh
The key's randomart image is:
+---[DSA 1024]----+
| =*=. o.. . |
| ..o o. o+.o . |
| E . ..o.+.o |
| . . ..o.= |
| o S.o o . |
| .o *.O. |
| o.=+o*..o |
| * ....o o |
| .. ..o |
+----[SHA256]-----+
Please enter the password free login to SSH IP addres :192.168.0.250 ##输入要做免秘钥登录的ip地址
spawn ssh-copy-id -i /root/.ssh/id_dsa.pub root@192.168.0.250
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_dsa.pub"
The authenticity of host '192.168.0.250 (192.168.0.250)' can't be established.
ECDSA key fingerprint is SHA256:wbK7TsRJ2JB/w7JKLmOmaCx8Y/jlDEtd1bGkBP6sQ60.
ECDSA key fingerprint is MD5:ed:ea:64:b7:f9:b7:c6:25:22:32:d1:94:39:ad:51:0d.
Are you sure you want to continue connecting (yes/no)? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.0.250's password:
Number of key(s) added: 1
Now try logging into the machine, with: "ssh 'root@192.168.0.250'"
and check to make sure that only the key(s) you wanted were added.
3、验证效果,登录192.168.0.250 已经免密登录
[root@hhhh opt]# ssh 192.168.0.250
Last login: Sat May 30 09:11:29 2020 from 192.168.0.20