关于linux:Linux-服务器之间使用公钥实现免密码登录

22次阅读

共计 2301 个字符,预计需要花费 6 分钟才能阅读完成。

配置步骤

serverA 服务器:

[root@serverA ~]# su - usera
[usera@serverA ~]$ pwd
/home/usera
# 应用 RSA 生成密钥对
[usera@serverA ~]$ ssh-keygen -t 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. |
+-----------------+
# 查看生成的密钥对
[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
# 将公钥上传到 serverB 服务器的 userb 用户下
# ssh-copy-id -i ~/.ssh/id_rsa.pub "-p 10022 userb@10.124.84.20"
[usera@portalweb1 ~]$ ssh-copy-id userb@10.124.84.20
The authenticity of host '10.124.84.20 (10.124.84.20)' 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 '10.124.84.20' (RSA) to the list of known hosts.
userb@10.124.84.29's password: 
Now try logging into the machine, with "ssh'userb@10.124.84.20'", and check in:
  
 .ssh/authorized_keys
  
to make sure we haven't added extra keys that you weren't expecting.
# 查看 serverA 服务器上 usera 的公钥文件内容
[usera@serverA ~]$ cat .ssh/id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA2dpxfvifkpswsbu...

serverB 服务器:

# 查看 serverB 服务器 userb 用户下的 ~/.ssh/authorized_keys 文件
[userb@serverB ~]$ cat .ssh/authorized_keys
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEA2dpxfvifkpswsbu...
# 查看 authorized_keys 和 id_rsa 的权限是否为 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

serverA 服务器免明码登录 serverB 服务器:

[usera@serverA ~]$ ssh userb@10.124.84.20

拷贝公钥的办法

将公钥拷贝到指标服务器的 ~/.ssh/authorized_keys 文件中办法有如下几种:

1、将公钥通过 scp 拷贝到指标服务器上,而后追加到 ~/.ssh/authorized_keys 文件中,这种形式比拟麻烦。scp -P 22 ~/.ssh/id_rsa.pub user@host:~/

2、通过 ssh-copy-id 程序,就是我演示的办法,ssh-copyid user@host

3、能够通过cat ~/.ssh/id_rsa.pub | ssh -p 22 user@host‘cat >> ~/.ssh/authorized_keys',这个也是比拟罕用的办法,因为能够更改端口号。

正文完
 0