Linux VPS服务器开启SSH Key免密码登录

博主使用SSH登录VPS一直习惯用复杂密码+非22端口,然而这些天发现吃灰很久的小鸡。CPU进程都是满的,使用SSH登录VPS查看CPU占用率,发现SSH密码已被黑客爆了并安装了挖矿程序导致VPS一直负荷运行。尝试几次卸载挖矿程序都失败了,最后以重装系统告终。可怕~赶紧换用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
Last modification:January 27th, 2021 at 05:31 pm
If you think my article is useful to you, please feel free to appreciate