跳转至

Set SSH Non Secret Login

Linux 设置 SSH 免密登录

日常使用的 VPS 都是账号 + 密码的方式,密码方式容易被扫描或无限尝试(另外注意保存密钥信息或文件)

一. 生成密钥

首先生成密钥,登录到 Linux VPS 上键入如下命令:

1
2
3
4
5
6
7
8
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
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:

中间会提示输入密码,如不想再对密钥加密码的话就直接输入 2 次回车即可

PS:为了实现统一管理,可以使用由 Master 的设备生成密钥,再将公钥发送至不同的 VPS,不必每个服务器都生成密钥

  1. 现使用 Master 的笔电设备生成密钥文件
$ ssh-keygen -t rsa -b 4096 -C "example@mail.com"
  1. 将生成后的公钥文件发至指定的服务器
$ ssh-copy-id -i id_rsa.pub -p 64596 root@137.175.66.188
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "id_rsa.pub"
The authenticity of host '[137.175.66.188]:64596 ([137.175.66.188]:64596)' can't be established.
ED25519 key fingerprint is SHA256:RnvAKIXEFOLOcW4kYA81bGjNEdFp/ElQxkIxdPrZXj4.
This key is not known by any other names.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@137.175.66.188's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh -p 64596 'root@137.175.66.188'"
and check to make sure that only the key(s) you wanted were added.
  1. 按提示操作成功后进行 ssh 测试远程
$ ssh -p 64596 root@137.175.66.188

此时可能还需要密码验证进入,如正常进入其实是正常的,因为 VPS 中的密码验证还未修改

二. 修改验证

远程登录 VPS 后关闭密码登录的方式

1
2
3
4
5
6
$ vim /etc/ssh/sshd_config
# 将此注释去掉,密码登录方式改为no
PasswordAuthentication no
# 将此注释去掉,密钥登录方式改为yes
PubkeyAuthentication yes
$ systemctl restart sshd

最后重启 sshd 服务令其生效,后面直接 ssh 即可免密登录,如使用 Terminal + Password 就会提示如下类似的信息

👤 Authenticating to "137.175.66.188":"64596" as "root"

❗ Disabling authentication using publickey: Private Key is empty

⚙️ Available client authentication methods: password,keyboard-interactive

⚙️ Authentication that can continue: gssapi-with-mic,publickey

😨 No more authentication methods to try