ssh 无密码登录要使用公钥与私钥。linux下可以用用ssh-keygen生成公钥/私钥对,下面我以CentOS为例。
机器A(192.168.254.128)与机器B(192.168.254.139)之间实现免秘钥登录。
1:在机器A下生成公钥/私钥对
[yuan@localhost ~]$ ssh-keygen -t rsa -P ''
-P表示密码,-P '' 就表示空密码,也可以不用-P参数,这样就要三车回车,用-P就一次回车。
它在/home/yuan下生成.ssh目录,.ssh下有id_rsa和id_rsa.pub。
产生如下提示,直接回车,默认路径(.ssh/id_rsa)下生成
Enter file in which to save the key (/home/yuan/.ssh/id_rsa):
内容如下:
The key fingerprint is:
34:ff:79:c1:88:60:95:f0:c1:8b:c0:ac:0d:54:6a:ff yuan@localhost.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
| ..+. .oo. |
| ..+ oo. |
| o+ .=... |
| ....o.+.. o |
| . S o . o |
| . . . . |
| E o . |
| . |
| |
+-----------------+
2:将生成的id_rsa.pub添加到.ssh/authorzied_keys文件里,并为authorzied_keys添加权限。
[yuan@localhost .ssh]$ cat id_rsa.pub >> authorized_keys
[yuan@localhost .ssh]$ chmod 600 authorized_keys
3:重启SSH
[yuan@localhost .ssh]$ service sshd restart
非root用户,记得加sudo。
4:将文件分发给B,B重新启动ssh
[yuan@localhost .ssh]$ scp ~/.ssh/* yuan2@192.168.254.129:~/.ssh/
登录的机子可有私钥,被登录的机子要有登录机子的公钥。这个公钥/私钥对一般在私钥宿主机产生。
coder这么做,直接把公钥私钥都发给B机,这样AB可相互登录,省的麻烦。
上面是用rsa算法的公钥/私钥对,当然也可以用dsa(对应的文件是id_dsa,id_dsa.pub)。