专业的编程技术博客社区

网站首页 > 博客文章 正文

服务器密钥登录更安全(免密),三步去掉密码登录,安全快捷

baijin 2024-10-02 11:12:24 博客文章 6 ℃ 0 评论

由于最近总收到服务器正在被尝试暴力登录的短信,便下定决心改为秘钥登录了。

大致分三步。

背景介绍

用户:username

本地系统:macOS

服务器:CentOS

服务器账号:root

第一步、生成本地秘钥

1、输入下面命令然后三个回车就可以

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/username/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /Users/username/.ssh/id_rsa.
Your public key has been saved in /Users/username/.ssh/id_rsa.pub.

一般会生成到当前用户的主目录

下面代表生成成功了

Your identification has been saved in /Users/username/.ssh/id_rsa.
Your public key has been saved in /Users/username/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Xxxxxxxxxxxxxxx
The key's randomart image i
xxxxxxxxxxxxxx

如果本地已经有了就得注意了,重新生成后,公钥和私钥会发生变化,导致登录不了服务器。

千万要注意。

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/username/.ssh/id_rsa): 
/Users/username/.ssh/id_rsa already exists.
Overwrite (y/n)? n

2、这个时候直接使用cat命令查看公钥文件内容就可以了。

$ cat ~/.ssh/id_rsa.pub
xxxxxxxxxxxx


第二步、将本地的公钥放入到服务器

服务器上的文件路径为

# ll -ll /root/.ssh/authorized_keys 
-rw------- 1 root root 1551 1月  18 14:19 /root/.ssh/authorized_keys

使用vim把第二步显示的公钥内容添加到文件后面


第三步、关闭密码登录并重启服务

1、别搞错,是sshd_config 不是ssh_config。多一个d字母的文件

$ls /etc/ssh/
moduli       ssh_host_dsa_key      ssh_host_ecdsa_key.pub    ssh_host_rsa_key
ssh_config   ssh_host_dsa_key.pub  ssh_host_ed25519_key      ssh_host_rsa_key.pub
sshd_config  ssh_host_ecdsa_key   


2、修改登录配置

PasswordAuthentication yes
修改为
PasswordAuthentication no

4、重启ssh的服务

$ systemctl restart sshd

5、非法登录验证

$ssh root@1.1.1.1(示例ip)
Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

6、正常登陆

$ssh root@1.1.1.1(示例ip)
会进入到root目录


再也不用担心坏孩子尝试暴力破解了。

但一定要把本地的私钥在保存一份到别处备份,不然丢了后。服务器登录就得想别的办法解决了。比如通过云平台修改root密码,然后重启。或者找IDC吧。

如果本文对你有帮助,请转发,说不定你的朋友也需要它。

关注我,掌握更多编程技巧成倍提升工作效率。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表