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

为了确保主机安全,包括阿里云、腾讯云在内的云主机都开始推荐使用SSH Key登录并禁用root密码登录。前几天开通的京东云虽然也支持SSH Key,但是在允许SSH Key登陆的同时并没有禁用root密码登录,学习如何配置使用SSH Key登录并禁用root密码登录,特予以记录。

centos.jpg

一、生成SSH Key

ssh-keygen -t rsa

显示:

# ssh-keygen -t rsa
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:
23:90:47:f9:cb:ab:97:54:fb:1f:68:43:82:20:b3:c9 [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|      ..         |
|     o.          |
|    = o.         |
|     B.o .  .    |
|      EoS ....   |
|       .o..o ..  |
|         o .+ .. |
|          +. ... |
|        .o    .. |
+-----------------+

执行完毕后在/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
猜您喜欢

发表评论

icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif