SSH实现双向认证
由于经常需要使用scp在两台机器间拷贝文件,每次都输入密码太麻烦,于是按下面的步骤配置了一下,再使用ssh或scp登录远程机器时就不需输入密码了:
A主机:192.168.100.82
B主机:192.168.100.83
Linux/Unix双机建立信任
1.在A机生成证书
在A机root用户或其他用户下执行ssh-keygen命令,在需要输入的地方,直接回车,生成建立安全信任关系的证书。
[root@localhost ~]#ssh-keygen -t rsa
注意:在程序提示输入passphrase时直接输入回车,表示无证书密码。
上述命令将生成私钥证书id_rsa和公钥证书id_rsa.pub,存放在用户家目录的.ssh子目录中.
2.查看~/.ssh生成密钥的文件
[root@localhost ~]# ll /root/.ssh/
total 8
-rw------- 1 root root 1675 Apr 27 15:55 id_rsa
-rw-r--r-- 1 root root 400 Apr 27 15:55 id_rsa.pub
3.A对B建立信任关系
将A主机的公钥证书id_rsa.pub复制到机器B主机的root家目录的.ssh子目录中,同时将文件名更换为authorized_keys,此时需要输入B主机的root用户密码(还未建立信任关系)。建立了客户端到服务器端的信任关系后,客户端就可以不用再输入密码,就可以从服务器端拷贝数据了。
scp -r -P 22 /root/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys
如果做单向认证,这里已经可以实现A到B的免秘钥上传下载了.
4.B对A建立信任关系
在B机上执行同样的操作,建立B对A的信任关系。
[root@localhost ~]#ssh-keygen -t rsa
root@localhost ~]# ll /root/.ssh/
total 8
-rw-r--r-- 1 root root 1678 Apr 27 15:59 authorized_keys
-rw------- 1 root root 1675 Apr 27 15:55 id_rsa
-rw-r--r-- 1 root root 400 Apr 27 15:55 id_rsa.pub
将B主机的公钥证书id_rsa.pub复制到机器A主机的root家目录的.ssh子目录中,同时将文件名更换为authorized_keys
scp -r -P 22 /root/.ssh/id_rsa.pub [email protected]:/root/.ssh/authorized_keys
这样A和B主机就可以互相传文件而不需要密码了.
如果连接反应慢,请修改以下两参数
/etc/ssh/sshd_config
GSSAPIAuthentication no
UseDNS no
重启sshd
service sshd restart
################################################################################
二.使用ssh-keygen和ssh-copy-id三步实现SSH无密码登录
由于上面这样复制文件很麻烦,以下给出更为方便的方法,在做单向ssh认证时都在本端计算机进行, 即使用ssh-copy-id进行操作,它可以直接在对端生成authorized_keys文件.
[user1@localhost ~]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/user1/.ssh/id_rsa):
Created directory '/home/user1/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/user1/.ssh/id_rsa.
Your public key has been saved in /home/user1/.ssh/id_rsa.pub.
The key fingerprint is:
da:e3:f0:2b:93:47:15:4d:a1:dc:68:00:07:ec:41:87 user1@localhost
The key's randomart image is:
+--[ RSA 2048]----+
| o+++ oo. |
| Eo o.+. |
| . . =.. |
| . .. |
| S. |
| o. |
| ooo |
| ++.. |
| ++. |
+-----------------+
[user1@localhost ~]$ ssh-copy-id -i .ssh/id_rsa.pub "-p 6168 [email protected]"
The authenticity of host '[192.168.3.192]:6168 ([192.168.3.192]:6168)' can't be established.
RSA key fingerprint is 8d:8c:22:67:68:f7:ad:1e:83:f3:4c:d4:32:d8:53:d6.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '[192.168.3.192]:6168' (RSA) to the list of known hosts.
[email protected]'s password:
Now try logging into the machine, with "ssh '-p 6168 [email protected]'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.
[user1@localhost ~]$
#这样就会自动在192.168.3.192远端机器的.ssh目录下创建authorized_keys文件.