There are many places in the actual production environment that need to use password-free login, such as GFS distributed file system, ansible, etc. If there are not many hosts that require password-free login, you can use commands to log in to each host device without password; if there are a large number of hosts that need to log in without password, then set up password-free login for each host It's very annoying. At this time, a script is needed to realize batch password-free login.
Introduction to the principle of ssh password-free login
Assuming that PC1 wants to log in to PC2 with SSH without password , then PC1 first needs to create a key pair ( ssh-keygen -t rsa
), and then copy the public key to PC2 ( ssh-copy-id root@PC2IP地址
)
This time we can use ls -lA
to view hidden files in the home directory
enter .ssh
to view the directory
is assumed that the device 15 wants to avoid dense login device 16 , the device 15 inside id_rsa.pub
and 16 facilities in the authorized_keys
content is the same
ssh login script-free secret
[root@15 ~]# vim ssh_patch.sh
#!/bin/bash
#ssh批量免密登录
#你需要新建一个host_ip.txt的文件,用于存放IP地址
#你需要修改下面的密码
password=123456
#判断有没有安装expect,没有则安装
if ! rpm -q expect > /dev/null
then
echo "###expect 未安装,现在安装###"
yum install -y expect &>/dev/null
if [ $? -ne 0 ]
then
echo "###expect 安装失败###"
exit 1
fi
fi
#生成ssh密钥对
/usr/bin/expect <<-EOF
spawn ssh-keygen -t rsa
expect "(/root/.ssh/id_rsa)" {
send "\r"}
expect "(empty for no passphrase)" {
send "\r"}
expect "again" {
send "\r"}
expect eof
EOF
#从host_ip.txt文件中获取主机IP地址信息
for IP in $(more host_ip.txt)
do
if [ -n $IP ]
then
/usr/bin/expect <<-EOF
spawn ssh-copy-id root@$IP
expect "yes/no" {
send "yes\r"}
expect "password" {
send "$password\r"}
expect eof
EOF
else
echo "The IP is NULL !!!"
fi
done
Enter the host_ip.txt
IP address of the host that requires password-free login , in the format of one IP address per line
[root@15 ~]# vi host_ip.txt
20.0.0.26
20.0.0.27
There are two ways to execute the script, one is to display the information, the other is to not display the information, if there are many hosts, you can use the second
① Execute the script directly, the execution information is displayed, there is a lot of information, you can see the error message
. ssh_patch.sh
② Redirect output to /dev/null, no information is displayed
. ssh_patch.sh &> /dev/null
View the hosts that have successfully logged in without secret