1.客户端生成公私钥
本地客户端生成公私钥:(一路回车默认即可)
root@test:~# ssh-keygen
上面这个命令会在用户目录.ssh文件夹下创建公私钥
root@test:~# cd ~/.ssh/
root@test:~/.ssh# ls
authorized_keys id_rsa id_rsa.pub
#######################################
下创建两个密钥:
id_rsa (私钥)
id_rsa.pub (公钥)
2.上传公钥到服务器
这里测试用的服务器地址为:192.168.X.X
root@test:~/.ssh# ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.X.X
#上面这条命令是写到服务器上的ssh目录下去了
root@test:~# cat ~/.ssh/authorized_keys
#可以看到客户端写入到服务器的 id_rsa.pub (公钥)内容
3.测试免密登录
客户端通过ssh连接远程服务器,就可以免密登录了。
root@test:~# ssh root@192.168.X.X
备注操作批量脚本
#!/bin/bash
if ! rpm -q expect > /dev/null
then
echo "###expect 未安装,现在安装###"
yum install -y expect &>/dev/null ###安装expect###
if [ $? -ne 0 ]
then
echo "###expect 安装失败###"
exit 1
fi
fi
if [ ! -f ~/.ssh/id_rsa ]
then
echo "###请按3次enter键###"
ssh-keygen -t rsa
fi
passwd="密码"
ssh_expect () {
expect -c "set timeout -1;
spawn ssh-copy-id -f $1
expect {
"yes/no" { send -- yes\r;exp_continue;}
"password:" { send -- $2\r;exp_continue;}
eof:
}";
}
for ip in `cat hosts.txt |awk '{print $1}'`
do
ssh_expect $ip $passwd
done