ssh 无密码登录要使用公钥与私钥。Linux下可以用用ssh-keygen生成公钥/私钥对。
有机器A,B(192.168.0.32)。现想A通过ssh免密码登录到B。
1.在A机下生成公钥/私钥对。
➜ ~ ssh-keygen -t rsa -P ''
-P表示密码,-P '' 就表示空密码,也可以不用-P参数,这样就要三车回车,用-P就一次回车。
该命令将在/root/.ssh目录下面产生一对密钥id_rsa和id_rsa.pub。
一般采用的ssh的rsa密钥:
id_rsa 私钥
id_rsa.pub 公钥
下述命令产生不同类型的密钥
ssh-keygen -t dsa
ssh-keygen -t rsa
ssh-keygen -t rsa1
2.把A机目录~/.ssh/下的所有文件复制到B机~/.ssh/目录下,先要在B机上创建~/.ssh 这个目录,用scp复制。
[xqzhang@PEKdev032 ~]$ mkdir .ssh
➜ ~ scp .ssh/* 192.168.0.32:/home/xqzhang/.ssh/
复制id_rsa.pub到authorized_keys文件里,
[xqzhang@PEKdev032 ~]$ chmod 700 .ssh
[xqzhang@PEKdev032 .ssh]$ chmod 600 *
由于还没有免密码登录的,所以要输入一次B机的root密码。
authorized_keys的权限要是600!!!
.ssh目录的权限要是700!!!
3.A机登录B机。
ssh -l xqzhang 192.168.0.32
第一次登录是时要你输入yes。
现在A机可以无密码登录B机了。
小结:登录的机子可有私钥,被登录的机子要有登录机子的公钥。这个公钥/私钥对一般在私钥宿主机产生。上面是用rsa算法的公钥/私钥对,当然也可以用dsa(对应的文件是id_dsa,id_dsa.pub)
附:
vim ssh-dist.sh
#!/bin/bash
yum -y install sshpass
# confirm the user of the operation
echo "The current user is `whoami`"
# 1.generate the key pair
# 判断key是否已经存在,如果不存在就生成新的key
if [ -f ~/.ssh/id_rsa ];then
echo "rsa ssh-key file already exists" /bin/true
else
echo "rsa ssh-key file does not exists"
ssh-keygen -t rsa -f ~/.ssh/id_rsa -P "" >/dev/null 2>&1
if [ $? -eq 0 ];then
echo "generate rsa ssh-key" /bin/true
else
echo "generate rsa ssh-key" /bin/false
exit 1
fi
fi
# 2.distribution public key
for host in $(cat ./ssh-ip | grep -v "#" | grep -v ";" | grep -v "^$")
do
ip=$(echo ${host} | cut -f1 -d ":")
password=$(echo ${host} | cut -f2 -d ":")
user=root
port_ip=$(echo ${user}@${ip})
sshpass -p "${password}" ssh-copy-id -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=no ${port_ip}
if [ $? -eq 0 ];then
echo "${ip} distribution public key" /bin/true
else
echo "${ip} distribution public key" /bin/false
exit 1
fi
done
vim ssh-ip
# 格式如下:
ip:密码