ssh-copy-id使用密钥进行免密登录
ssh使用密钥登录过程:主机A创建公钥私钥,并将公钥复制到主机B的用户下,然后主机A使用保存私钥的用户登录到主机B对应保存公钥的用户。
-
生成密钥使用的命令:ssh-keygen -t rsa
-
拷贝密钥使用的命令:ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.26.167
下面编写基于bash的sshpass.sh脚本完成免密登录过程
在主机A上执行vi /home/sshpass.sh将以下内容保存为sh文件。
#!/bin/bash
# This operation copies the ssh key(s) to the target host and enables password free login
# @author xincono 2020-04-14 16:10
echo 'This operation copies the ssh key(s) to the target host and enables password free login'
if [ ! -s "/root/.ssh/id_rsa.pub" ]; then
echo "ssh-keygen -t rsa"
ssh-keygen -t rsa
fi
read -p "Enter target host address: " CONFIRM
if [ -n "$CONFIRM" ]; then
HOST=$CONFIRM
ssh ${HOST} -o PreferredAuthentications=publickey -o StrictHostKeyChecking=no "date" >/dev/null 2>&1
if [ $? -ne 0 ]; then
ssh-copy-id -i /root/.ssh/id_rsa.pub root@${HOST}
echo "OK"
else
echo "The ssh key(s) already exists."
fi
fi
执行sh /home/sshpass.sh命令,并按照提示按回车以及输入IP地址和密码即可完成root用户免密操作。