ssh免密码登录的配置方法
目标:服务器ServerA上面的用户usera,免密码登录到服务器ServerB上面的用户userb.
步骤:
一. 先使用usera登录到ServerA服务器
[root@serverA ~]# su - usera
[usera@serverA ~]$ pwd
/home/usera
二. 在serverA上生成密钥对
[usera@serverA ~]$ ssh-keygen -t rsa #指定加密算法为rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/usera/.ssh/id_rsa): #保存私钥的文件全路径
Created directory '/home/usera/.ssh'.
Enter passphrase (empty for no passphrase): #密码可以为空
Enter same passphrase again:
Your identification has been saved in /home/usera/.ssh/id_rsa. #生成私钥
Your public key has been saved in /home/usera/.ssh/id_rsa.pub. #生成公钥
The key fingerprint is:
39:f2:fc:70:ef:e9:bd:05:40:6e:64:b0:99:56:6e:01 usera@serverA
The key's randomart image is:
+--[ RSA 2048]----+
| Eo* |
| @ . |
| = * |
| o o . |
| . S . |
| + . . |
| + . .|
| + . o . |
| .o= o. |
+-----------------+
此时会在/home/usera/.ssh目录下生成密钥对.
[usera@serverA ~]$ ls -la .ssh
总用量 16
drwx------ 2 usera usera 4096 8月 24 09:22 .
drwxrwx--- 12 usera usera 4096 8月 24 09:22 ..
-rw------- 1 usera usera 1675 8月 24 09:22 id_rsa #私钥
-rw-r--r-- 1 usera usera 399 8月 24 09:22 id_rsa.pub #公钥
三. 将刚刚生成的公钥id_rsa.pub上传到ServerB 服务器上,以userb用户登录到ServerB,然后将刚刚上传的id_rsa.pub追加到~/.ssh/authorized_keys中.
[usera@serverA ~]$ scp -p 22 ~/.ssh/id_rsa.pub userb@ServerB:~/.ssh/tmp/
#将公钥id_rsa.pub上传到ServerB中的~/.ssh/tmp/目录中,需要输入userb@ServerB的密码
[usera@serverA ~]$ ssh –p 22 userb@ServerB
#从ServerA中用userb登录到ServerB
[userb@serverB ~]$ cat ~/.ssh/tmp/id_rsa.pub >> ~/.ssh/authorized_keys
#将上传的公钥id_rsa.pub追加到~/.ssh/authorized_keys中
注意
.ssh目录的权限为700,其下文件authorized_keys和私钥的权限为600。否则会因为权限问题导致无法免密码登录。我们可以看到登陆后会有known_hosts文件生成。
[useb@serverB ~]$ ls -la .ssh
total 24
drwx------. 2 useb useb 4096 Jul 27 16:13 .
drwx------. 35 useb useb 4096 Aug 24 09:18 ..
-rw------- 1 useb useb 796 Aug 24 09:24 authorized_keys
-rw------- 1 useb useb 1675 Jul 27 16:09 id_rsa #私钥
-rw-r--r-- 1 useb useb 397 Jul 27 16:09 id_rsa.pub #公钥
-rw-r--r-- 1 useb useb 1183 Aug 11 13:57 known_hosts
这样做完之后我们就可以免密码登录了:
[usera@serverA ~]$ ssh userb@serverB
另外,将usera@ServerA的公钥追加到userb@ServerB的~/.ssh/authorized_keys文件中方法有如下几种:
将公钥通过scp拷贝到服务器ServerB上,然后在ServerB上将公钥追加到~/.ssh/authorized_keys文件中,也就是上面我演示的方法.
通过如下命令:
[usera@serverA ~]$ cat ~/.ssh/id_rsa.pub | ssh -p 22 userb@ServerB 'cat >> ~userb/.ssh/authorized_keys'
这个也是比较常用的方法,因为可以更改端口号。
通过ssh-copy-id程序,用命令ssh-copyid userb@ServerB即可,具体说明如下:
[usera@ServerA ~]$ ssh-copy-id userb@ServerB The authenticity of host 'ServerB' can't be established. RSA key fingerprint is f0:1c:05:40:d3:71:31:61:b6:ad:7c:c2:f0:85:3c:cf. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added 'ServerB' (RSA) to the list of known hosts. userb@ServerB's password: Now try logging into the machine, with "ssh 'userb@ServerB'", and check in: .ssh/authorized_keys to make sure we haven't added extra keys that you weren't expecting.
这个时候usera的公钥文件内容会追加写入到userb的 .ssh/authorized_keys 文件中.