前言

经常我们的服务器在深夜,往往会遭到Nmap 扫描,然后有很多ip 试探登录连接我们的服务器,那么我们该如何面对这种情况呢?

需求描述

分析Linux系统/var/log/secure安全日志文件,将黑客或者恶意登陆次数大于20次的IP地址加入Iptables防火墙黑名单;

实验步骤

  • 首先查看安全日志文件
[root@localhost ~]# cat  /var/log/secure|more
Jun  5 10:25:56 localhost sshd[10165]: Accepted password for root from 192.168.10.1 port 58525 ssh2
Jun  5 10:25:56 localhost sshd[10165]: pam_unix(sshd:session): session opened for user root by (uid=
0)
Jun  5 10:25:59 localhost sshd[10184]: Accepted password for root from 192.168.10.1 port 58528 ssh2
Jun  5 10:25:59 localhost sshd[10184]: pam_unix(sshd:session): session opened for user root by (uid=
0)
Jun  5 12:51:19 localhost sshd[10394]: Accepted password for root from 192.168.10.1 port 64063 ssh2
Jun  5 12:51:19 localhost sshd[10394]: pam_unix(sshd:session): session opened for user root by (uid=
0)
Jun  5 13:03:00 localhost sshd[10428]: pam_unix(sshd:auth): authentication failure; logname= uid=0 e
uid=0 tty=ssh ruser= rhost=192.168.10.1  user=root
Jun  5 13:03:00 localhost sshd[10428]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met 
by user "root"
Jun  5 13:03:02 localhost sshd[10428]: Failed password for root from 192.168.10.1 port 64400 ssh2
Jun  5 13:03:06 localhost sshd[10428]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met 
by user "root"
Jun  5 13:03:08 localhost sshd[10428]: Failed password for root from 192.168.10.1 port 64400 ssh2
Jun  5 13:03:14 localhost sshd[10428]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met 
--More--
  • 打印登录失败的ip
[root@localhost ~]# grep "Failed password" /var/log/secure |awk '{print$(NF-3)}'
192.168.10.1
192.168.10.1
192.168.10.1
192.168.10.1
192.168.10.10
192.168.10.10
192.168.10.10
192.168.10.10
192.168.10.10
192.168.10.10
192.168.10.10
192.168.10.10
192.168.10.10
[root@localhost ~]# 
  • 进行排序,统计次数
[root@localhost ~]# grep "Failed password" /var/log/secure |awk '{print$(NF-3)}'|sort|uniq -c|sort -nr
      9 192.168.10.10
      4 192.168.10.1
[root@localhost ~]# 
  • 匹配恶意登录次数大于5次的ip
[root@localhost ~]# grep "Failed password" /var/log/secure |awk '{print$(NF-3)}'|sort|uniq -c|sort -nr|awk '{if ($1>=5) print $2}'
192.168.10.10
[root@localhost ~]# 
  • 对匹配出来的做一个for循环,然后写入防火墙文件
[root@localhost ~]# for i in $(grep "Failed password" /var/log/secure|awk '{print $(NF-3)}'|sort|uniq -c|sort -nr|awk '{if($1>=5) print $2}');do sed -i "/lo/a -A INPUT -s $i -j DROP" /etc/sysconfig/iptables ;done

总结

运维安全在实际生产环境中有着很重要的地位,我们面对黑客疯狂扫描试探的时候,我就需要见流量封杀IP。如何快速封杀IP角色需要我们掌握数量掌握linux命令。特别是awk,sed。在我们脚本中很常用。一定要掌握好。

最后修改:2024 年 04 月 21 日
欸嘿,不如点一杯奶茶给我吧