【shell脚本】截取恶意端口ip,禁止远程登录22端口auto_deny_ip.sh

[root@rhel8 shell]# cat auto_deny_ip.sh 
#!/bin/bash
# auto drop ssh failded IP address
# by author tanbaobao 2020/06/10

# 定义变量
SEC_FILE=/var/log/secure

# 为截取secure文件恶意ip 远程登录22端口,大于等于4次就写入防火墙 禁止再登录服务器22端口。
# egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}" 匹配IP. [0-9]表示任意一个数 {1,3}表示匹配1~3次
IP_ADDR=`tail -n 1000 /var/log/secure | grep "Failed password" | egrep -o "([0-9]{1,3}\.){3}[0-9]{1,3}" |sort -nr | uniq -c | awk '$1>=4 {print $2}'`
IPTABLE_CONF=/etc/sysconfig/iptables echo cat << EOF ++++++++++++++++++++++++++++++ welcome to use ssh login drop failed ip ++++++++++++++++++++++++++++++ +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++++-----------------------------------------++++++++++++++++++++++++++++++ EOF for i in `echo $IP_ADDR` do # 查看iptables配置文件是否含有提取的IP信息 cat $IPTABLE_CONF | grep $i >/dev/null if [ $? -ne 0 ];then # 判断iptables配置文件中是否存在已拒绝的IP,不存在,则添加,存在,则不添加。sed a 表示在匹配行后加入
   sed -i "/lo/a -A INPUT -s $i -m state --state NEW -n tcp -p tcp --dport 22 -j DROP" $IPTABLE_CONF else # 存在则打印提示信息 echo "This is $i is exist in iptables,Please exit ..." fi done # 重启防火墙配置生效 # systemctl restart firewalld # /etc/init.d/iptables restart
# 需要先保存下规则,不然重启会失败
iptables-save > /etc/sysconfig/iptables
systemctl restart iptables

 

posted @ 2020-06-10 12:52  HeiDi_BoKe  阅读(527)  评论(0编辑  收藏  举报