起因:之前租了一个腾讯云服务器,每次登录的时候都会弹出一个warning,提示有很多failed login,也就是有很多主机尝试登录你的服务器。
1、查看有哪些主机尝试过登录你的服务器:
[root@VM-4-12-centos ~]# lastb | head cirros ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) cirros ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) cirros ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) cirros ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) test ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) test ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) guest ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) guest ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) alarm ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00) alarm ssh:notty 119.53.57.50 Tue Dec 21 08:15 - 08:15 (00:00)
统计不同节点尝试登录的次数:
[root@VM-4-12-centos ~]# cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' | head 101.166.192.3=2 101.80.171.2=64 103.10.227.43=2 103.127.50.32=1 103.198.203.162=1 103.214.112.199=12 103.220.157.30=71 103.252.170.48=4 103.78.207.190=2 104.171.245.133=15
2、配置服务器,修改为密钥登录
为了防止服务器被暴力破解,一般的解决方案分为两类:
- 禁用root登录,不使用root登录,避免用户名和密码被猜到然后暴力破解,同时修改SSH端口(修改成五位),将密码更改的更复杂(强口令)
- 关闭密码登录,启用密钥登录,可以的说是安全系数最高的解决办法
本文记录的就是本地(windows)利用私钥去登录服务器。公钥相当于锁,私钥相当于钥匙。服务器保存公钥,客户端保存私钥,以后在客户端登陆时,就可以使用私钥来进行验证。
2.1、生成一对密钥
1)在服务器生成一对密钥(包含公钥和私钥)。
[root@VM-4-12-centos ~]# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):/root/.ssh/id_rsa
Created directory '/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:GwDhxaE+rU7GMPDwot0cuIzwZ41jv9NvDjrJ7VSmDkE root@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]-----+
2)查看生成的密钥。id_rsa是私钥,id_rsa.pub是公钥,(第一查看的时候authorized_keys 应该没有,这是下面追加写入的文件)
[root@VM-4-12-centos ~]# cd /root/.ssh/
[root@VM-4-12-centos .ssh]# ll
total 12
-rw------- 1 root root 401 Dec 21 10:07 authorized_keys
-rw------- 1 root root 1766 Dec 21 10:06 id_rsa
-rw-r--r-- 1 root root 401 Dec 21 10:06 id_rsa.pub
3)将公钥追加到keys文件中,并修改权限。
[root@VM-4-12-centos .ssh]# cat id_rsa.pub >> /root/.ssh/authorized_keys
[root@VM-4-12-centos .ssh]# chmod 600 authorized_keys
4)修改sshd_config,打开ssh服务器的密钥登陆功能 并关闭密码登录功能
vim /etc/ssh/sshd_config
打开密钥登录功能。
PubkeyAuthentication yes
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile .ssh/authorized_keys
关闭密码登录功能。yes 改为no
PasswordAuthentication no
重启服务
[root@VM-4-12-centos .ssh]# systemctl restart sshd.service
2.2 客户端配置私钥
1)将服务器中的私钥下载到本地,我使用的是Xftp(传输文件),Xshell (远程登录shell)。使用Xftp下载私钥。
2)Xshell 中配置密钥登录。(passwod可以取消掉,只保留public key)
选择下载到本地的私钥,进行连接配置。然后可以重新登录。