zl程序教程

您现在的位置是:首页 >  其他

当前栏目

Linux为指定ip开放/关闭端口

2023-03-20 15:34:15 时间

上一篇文章写到了fail2ban来屏蔽IP,可能是我配置的不对,所以除了拉黑之外,毫无作用,还是有成千上万的相同IP在试探密码,干脆写了个shell屏蔽IP的脚本。

获取破解服务器密码失败的IP统计代码:

cat /var/log/secure | awk '/Failed password/{print $(NF-3), $1,$2}' | sort | uniq -c | sort -nr

在linux中,防火墙屏蔽IP的代码如下:

firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address=95.19.175.62 port port=22 protocol=tcp drop"

-permanent示意永久封禁,--add-rich-rule示意添加规则,来源(source address)为95.19.175.62的IP,对22号端口将永久不能访问drop。

重启已生效:

firewall-cmd --reload

当然,一个个封IP会有点麻烦,可以写一个shell脚本,快速封禁。代码如下:

# !/bin/bash
# author:zxf
# drop ip from port 22
if [ $1 ];
then
        drop_ip=$1
        firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address='${drop_ip}' port port=22 protocol=tcp drop"
        firewall-cmd --reload
fi
echo "This is list rich rules"
firewall-cmd --zone=public --list-rich-rules

该脚本可接受一个参数,输入IP,则会自动将其拉入防火墙黑名单,并重启,其实与上面的代码是一样的,只不过写成了脚本形式;如果没有参数,则会直接列出当前的规则。需要注意的是,shell脚本中定义变量一定不要空格,写惯了python基本都会碰到这个坑!

sh dropIP22.sh 189.140.134.170

因为最近IP总是在变化,给测试带来了很多不方便,每次都要为一个IP开放很多端口,干脆也写了一个脚本,批量为某个IP开放端口,应该可以用for写的更简洁,后续再来修改吧。

#!/bin/bash
# author:zxf
# for test convenient, accept 2 parames, first is ip, second is "add" or "remove"
port1=3306
port2=80
port3=7890
port4=9200
port5=8000

if [ $1 ];
then
        ip=$1;
        strategy=$2;
        firewall-cmd --permanent --$strategy-rich-rule="rule family='ipv4' source address=$ip port port=$port1 protocol=tcp accept "
        firewall-cmd --permanent --$strategy-rich-rule="rule family='ipv4' source address=$ip port port=$port2 protocol=tcp accept "
        firewall-cmd --permanent --$strategy-rich-rule="rule family='ipv4' source address=$ip port port=$port3 protocol=tcp accept "
        firewall-cmd --permanent --$strategy-rich-rule="rule family='ipv4' source address=$ip port port=$port4 protocol=tcp accept "
        firewall-cmd --permanent --$strategy-rich-rule="rule family='ipv4' source address=$ip port port=$port5 protocol=tcp accept "
        firewall-cmd --reload
fi
echo "Rich rules below:"
firewall-cmd --list-all

和第一个脚本类似,只不过接受两个参数,一个用于删除IP的端口访问权限,一个用于添加IP对端口的访问权限。