配置使用SSH Key登录并禁用root密码登录

120次阅读
没有评论

配置使用 SSH Key 登录并禁用 root 密码登录

为了确保主机安全,包括阿里云、腾讯云在内的云主机都开始推荐使用 SSH Key 登录并禁用 root 密码登录。本文记录学习如何配置使用 SSH Key 登录并禁用 root 密码登录。

一、生成 SSH Key

ssh-keygen -t rsa

ssh-keygen -t rsa -b 2048 -v

显示:

# 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:
SHA256:N3EKOXQuTz0Tik****************0+vc4H5d0Leek root@default
The key's randomart image is:
+---[RSA 3072]----+
|    ...++ o..    |
|    .oo=.*.o..   |
|    ooooB =o=. . |
|   .o... * +.o= +|
|o o.    S =  = +o|
|.=o      . .o = .|
|oo           o E |
|.             .  |
|                 |
+----[SHA256]-----+

执行完毕后在 /root/.ssh/ 目录下生成了 2 个文件:

id_rsa 为私钥
id_rsa.pub 为公钥

私钥下载到本地电脑妥善保存,若用于 putty 还需通过 puttygen 转换为 putty 专属的 ppk 格式文件。为安全起见,私钥保存到本地后建议删除服务器端的私钥。

二、将公钥导入

cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys

三、修改 SSH 配置文件 /etc/ssh/sshd_config

将下列选项前的 #去掉

#RSAAuthentication yes
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys

修改为:

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile    .ssh/authorized_keys

四、禁用 root 密码登录

PasswordAuthentication yes

搜索,将之改为:

PasswordAuthentication no

保存后重启 SSH 服务。

systemctl restart sshd.service
service sshd restart

实际上其他 Linux 操作系统的步骤大同小异,例如 Ubuntu 同样适用以上方法。

最后保存重启 SSH 服务指令可能略有不同:

/etc/init.d/sshd reload
/etc/init.d/ssh restart
正文完
 
主机大巴
版权声明:本站原创文章,由 主机大巴 2023-11-08发表,共计1244字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)