如何设置SSH密钥

2017-10-18

如何设置SSH密钥

关于SSH密钥

使用SSH密钥提供更安全的登录虚拟专用服务器的方法,而不是单独使用密码。尽管密码最终可能会受到强力攻击而破裂,但SSH密钥几乎不可能通过暴力单独破译。生成一个密钥对为您提供两个长字符串:公钥和私钥。您可以将公钥放在任何服务器上,然后通过与具有私钥的客户端连接来解锁它。当两者匹配时,系统解锁而不需要密码。您可以通过用密码保护私钥来提高安全性。


第一步 - 创建RSA密钥对

第一步是在客户机上创建密钥对(很有可能这只是您的计算机):

$ ssh-keygen -t rsa

第二步 - 存储密钥和密码

进入Gen Key命令后​​,您还会得到以下几个问题:

Enter file in which to save the key (/home/demo/.ssh/id_rsa):

您可以按Enter键,将文件保存到用户的家中(在这种情况下,我的示例用户称为演示)。

Enter passphrase (empty for no passphrase):

是否要使用密码?输入密码确实有其优点:密钥的安全性,无论加密如何,仍然取决于其他人不可见的事实。如果受密码保护的密钥属于未经授权的用户拥有,则他们将无法登录到其关联的帐户,直到找出密码,为黑客用户购买一些额外的时间。当然,使用密码短语的唯一缺点是在每次使用密钥对时都必须输入密码。

整个关键代码过程如下所示:

ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/demo/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/demo/.ssh/id_rsa.
Your public key has been saved in /home/demo/.ssh/id_rsa.pub.
The key fingerprint is:
4a:dd:0a:c6:35:4e:3f:ed:27:38:8c:74:44:4d:93:67 demo@a
The key's randomart image is:
+--[ RSA 2048]----+
|          .oo.   |
|         .  o.E  |
|        + .  o   |
|     . = = .     |
|      = S = .    |
|     o + = +     |
|      . o + o .  |
|           . o   |
|                 |
+-----------------+

公钥位于/home/demo/.ssh/id_rsa.pub

私钥(identification)位于/home/demo/.ssh/id_rsa


第三步 - 复​​制公钥

一旦生成了密钥对,现在是将公钥放在我们想要使用的虚拟服务器上的时候了。

您可以使用ssh-copy-id命令将公钥复制到新机器的authorized_keys文件中。请确保在以下替换示例用户名和IP地址。

$ ssh-copy-id user@123.45.56.78

或者,您可以使用SSH粘贴密钥:

$ cat ~/.ssh/id_rsa.pub | ssh user@123.45.56.78 "mkdir -p ~/.ssh && cat >>  ~/.ssh/authorized_keys"

无论您选择了哪个命令,都应该看到:

The authenticity of host '12.34.56.78 (12.34.56.78)' can't be established.
RSA key fingerprint is b1:2d:33:67:ce:35:4d:5f:f3:a8:cd:c0:c4:48:86:12.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '12.34.56.78' (RSA) to the list of known hosts.
user@12.34.56.78's password: 
Now try logging into the machine, with "ssh 'user@12.34.56.78'", and check in:

  ~/.ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

现在您可以继续登录user@12.34.56.78,不会提示您输入密码。但是,如果您设置了密码,那么您将被要求输入密码(当您日后登录时)。


可选步骤四 - 禁用 root 用户使用密码登录

将SSH密钥复制到您的服务器后,确保只能使用SSH密钥登录,您可以继续进行限制,只能通过SSH密钥进行root登录。

为了做到这一点,打开SSH配置文件:

sudo nano /etc/ssh/sshd_config

在该文件中,找到包含PermitRootLogin并修改它的行,以确保用户只能使用其SSH密钥进行连接:

PermitRootLogin without-password

重启ssh服务,使配置生效:

reload ssh
https://www.digitalocean.com/community/tutorials/how-to-set-up-ssh-keys--2