Centos密钥登陆,解决云服务器被尝试登陆问题

时间:2022-07-22
本文章向大家介绍Centos密钥登陆,解决云服务器被尝试登陆问题,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

1、云主机,每次上都有如下提示(各种被扫描和攻击…)

Last failed login: Tue Dec 12 07:55:36 CST 2017 from 219.146.144.254 on ssh:notty

There were 14011 failed login attempts since the last successful login.

Last login: Mon Dec 11 09:23:25 2017 from 180.110.80.73

研究后发现配置ssh密钥登陆并关闭密码登陆可以解决这个问题.

2、ssh登陆原理简单说明

公钥相当于锁,私钥相当于钥匙。
生成公钥和私钥,并把公钥上传到服务器。以后在客户端登陆时,就可以使用私钥来进行验证。不再需要用户名和密码登陆 ,大大提高了服务器安全性。

3、生成ssh密钥

[root@iZ2zeir6vcnpz8qw3t455tZ ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/ywm/.ssh/id_rsa):
Created directory '/home/ywm/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/ywm/.ssh/id_rsa.
Your public key has been saved in /home/ywm/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:GwDhxaE+rU7GMPDwot0cuIzwZ41jv9NvDjrJ7VSmDkE ywm@iZ2zeir6vcnpz8qw3t455tZ
The key's randomart image is:
+---[RSA 2048]----+
|    ooo.         |
|   . +.          |
|o   o E          |
| = o o .         |
|o * + o S o      |
|o* B * . *       |
|o = &.o+=        |
|   B o==o..      |
|    . +=o+o      |
+----[SHA256]-----+

查看生成的密钥.id_rsa是私钥,id_rsa.pub是公钥

[root@iZ2zeir6vcnpz8qw3t455tZ ~]# cd /root/.ssh/
[root@iZ2zeir6vcnpz8qw3t455tZ .ssh]# ls
authorized_keys  id_rsa  id_rsa.pub  known_hosts

将公钥追加到keys文件中

[root@iZ2zeir6vcnpz8qw3t455tZ .ssh]# cat id_rsa.pub >> /root/.ssh/authorized_keys

将权限改为只有当前用户可读可写,保证安全

[root@iZ2zeir6vcnpz8qw3t455tZ .ssh]# chmod 600 authorized_keys

4、打开ssh服务器的密钥登陆功能

# 修改SSH的配置文件/etc/ssh/sshd_config
[root@iZ2zeir6vcnpz8qw3t455tZ ~]# vim /etc/ssh/sshd_config
#PubkeyAuthentication yes
#AuthorizedKeysFile .ssh/authorized_keys

# 去除上面2行前面的注释,保存后重启SSH服务。
[root@iZ2zeir6vcnpz8qw3t455tZ ~]# systemctl restart sshd.service

5、使用windows下的ssh客户端配置密钥连接服务器

新建一个会话,并选择public-key的方式连接

浏览选择刚下载的私钥文件.确定

登陆成功!

6、关闭密码登录

# 修改SSH的配置文件/etc/ssh/sshd_config
[root@iZ2zeir6vcnpz8qw3t455tZ ~]# vim /etc/ssh/sshd_config
PasswordAuthentication yes
修改为:
PasswordAuthentication no
# 保存后重启SSH服务。
[root@iZ2zeir6vcnpz8qw3t455tZ ~]# systemctl restart sshd.service