ssh 无密码登录要使用公钥与私钥。通过andy128.com(192.168.12.128)linu主机使用root用户登陆andy129.com(192.168.12.129)linu主机的时候无需输入密码直接登陆。
1、 服务器环境
网络环境:
系统环境: CentOS 6.5 2.6.32x86_64
2、 生成密钥对
在andy128.com机器上建立dsa key,生存public key与private key。
private key和public key仅需要建立一次就可以了。
[root@andy128 ~]# ssh-keygen -t dsa
#ssh-keygen 是生成密钥的工具,-t参数指建立密钥的类型,这里建议dsa类型密钥。
#也可以执行ssh-keygen -t rsa 来建立rsa类型密钥。
#RSA与DSA加密算法的区别。
#RSA,是一种加密算法(PS: RSA也可以进行数字签名的),简写来由是Ron Rivest、Adi Shamir 和Leonard Adleman这三个人名字的第一个字母连接起来就是RSA。
#DSA就是数字签名算法的英文全称的简写,即Digital Signature Algorithm,RSA可以进行加密,也可以进行数字签名实现认证,而DSA只能用于数字签名从而使用认证
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa): #设置密钥保存路径,默认一路回车
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_dsa.#这是private key的路径
Your public key has been saved in /root/.ssh/id_dsa.pub.#这是public key的路径
The key fingerprint is:
26:e5:df:de:4b:14:86:d2:cf:8c:7e:e2:f4:fe:a8:c3 root@andy128.com
[root@andy128 ~]# ll .ssh/
total 8
-rw-------. 1 root root 668 Feb 18 20:30 id_dsa
-rw-r--r--. 1 root root 606 Feb 18 20:30 id_dsa.pub
#.ssh目录权限为700,.ssh/id_dsa权限为600,.ssh/id_dsa.pub权限为644
3、 分发密钥
[root@andy128 ~]# cd .ssh/
[root@andy128 .ssh]# ssh-copy-id -i id_dsa.pub root@192.168.12.129
#把id_dsa.pub拷贝到192.168.9.128的wiki家目录下的.ssh目录即可(需要改名,因为在sshd_config里面定义了“#AuthorizedKeysFile .ssh/authorized_keys”),ssh-copy-id为系统自带的shell脚本,可以用来分发公钥。
The authenticity of host '192.168.12.129 (192.168.12.129)' can't be established.
RSA key fingerprint is fe:50:93:33:6c:71:93:3e:3e:fd:23:b0:90:2c:a8:53.
Are you sure you want to continue connecting (yes/no)? yes#输入yes在本地添加ssh公钥信息。该信息默认会被添加到本地的~/.ssh/known_hosts文件中。
Warning: Permanently added '192.168.12.129' (RSA) to the list of known hosts.
root@192.168.12.129's password: #输入密码
Now try logging into the machine, with "ssh 'root@192.168.12.129'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
4、 远程登陆测试
[root@andy128 .ssh]# ssh root@192.168.12.129
Last login: Thu Feb 18 20:07:27 2016 from 192.168.12.1
[root@andy129 ~]# ifconfig | grep "inet addr"
inet addr:192.168.12.129 Bcast:192.168.12.255 Mask:255.255.255.0
inet addr:127.0.0.1 Mask:255.0.0.0
[root@andy129 ~]# hostname
andy129.com