VPS 服务器开启 SSH Key 登录

使用 SSH 登录 VPS 一直习惯用复杂密码+非 22 端口,为了方便和安全赶紧换用 Key 秘钥登录。

生成秘钥

先用 SSH+密码方式登录 VPS, 输入以下命令生成一对秘钥, 默认回车即可

ssh-keygen

终端中会出现提示

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:cTSMnqP5zXAer21hc9UtPJA8ZU2HYdEUiFwTyna0Hjw root@debian
The key's randomart image is:
+---[RSA 2048]----+
|         +oo=+B*+|
|        .o+=.=o.o|
|       ...=.E+   |
|        ++ o=o   |
|       oS.  .+ ..|
|      o . o . = o|
|       . * + o o |
|        . B +    |
|          .*     |
+----[SHA256]-----+

保存私钥

使用 cat 命令查看 VPS 生成的私钥,在本机新建一个文本,将私钥保存下来并命名为 「id_rsa」 不要后缀名,将它放到你想放的位置,一般~/.ssh

cat /root/.ssh/id_rsa

或者使用 scp 命令将私钥 id_rsa 从远程复制到本地/Users/july/Downloads/路径下 root@127.0.0.1 自行替换用户 @你的 IP

scp -P 22 root@127.0.0.1:/root/.ssh/id_rsa /Users/july/Downloads/

配置公钥

SSH+Key 登录, 需将 VPS 的公钥名字改成 authorized_keys

cd /root/.ssh/
mv id_rsa.pub authorized_keys
# 修改公钥为只有属主有读写权限 (安全考虑)
chmod 600 authorized_keys
# 修改 SSH 目录为只有属主有读写执行权限 (安全考虑)
chmod 700 /root/.ssh

开启 SSH+Key 登录

vi 命令编辑 sshd_config

vi /etc/ssh/sshd_config

找到以下两个参数,如果没有可以自行加上去,前面如果有 #需要先删除掉 #注释

RSAAuthentication no
PubkeyAuthentication no

将以上两个参数后的 no 改为 yes 即可 (一般默认就是 yes 不用改) 。

关闭 SSH+密码登录

vi 命令编辑 sshd_config

vi /etc/ssh/sshd_config

找到以下这个参数,如果没有可以自行加上去,前面如果有 #需要先删除掉 #注释

PasswordAuthentication yes

将这个参数后的 yes 改为 no 即可

SSH+Key 登录

SSH+Key 配置好后就可以重启 SSH 服务,进行登录了

/etc/init.d/ssh restart

使用 SSH+Key 登录

ssh -p aaa root@xxx.xxx.xxx.xxx -i ~/.ssh/id_rsa

注意:aaa: 端口
~/.ssh/id_rsa: 本机上私钥文件路径

如果用 SSH+Key 登录 VPS 服务器时, 终端中显示下面内容:

Permissions 0644 for 'id_rsa' are too open.
It is required that your private key files are NOT accessible by others.
This private key will be ignored.

本机上的私钥文件权限太大, 被忽略使用。在本机上执行以下命令, 修改私钥文件的权限即可。

chmod 0600 id_rsa
THE END