起因:之前租了一個騰訊雲服務器,每次登錄的時候都會彈出一個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)
選擇下載到本地的私鑰,進行連接配置。然后可以重新登錄。