Linux屏蔽国外IP简便方法

1. 安装ipset:

RedHat:

yum install ipset

Debian:

apt-get install ipset

1.2#建表

ipset create china hash:net hashsize 10000 maxelem 1000000

1.3#批量增加中国IP到ipset的china表

cd /root

#以下内容保存成脚本执行即可比如

vim chinaip.sh

输入:

#!/bin/bash
rm -f cn.zone
wget http://www.ipdeny.com/ipblocks/data/countries/cn.zone
for i in `cat cn.zone`
do
    ipset add china $i 
done

之后

sh chinaip.sh

2. 创建规则文件(vim iptabls.rule):

*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -m set --match-set china src -p tcp -m tcp --dport 1:65535 -j ACCEPT
-A INPUT -m set --match-set china src -p udp -m udp --dport 1:65535 -j ACCEPT
-A INPUT -p udp -m udp --dport 16384:32768 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -s 10.0.0.0/8 -j ACCEPT
-A INPUT -s 172.18.0.0/16 -j ACCEPT
-A INPUT -s 192.168.0.0/16 -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
COMMIT

3. 导入规则文件:

# 导入规则文件

iptables-restore < iptabls.rule 

# 应用生效 CentOS9 不用下面这个命令即可生效,且无下面这个命令

iptables-apply 

4. 查看iptables规则:

root@opensips:~# iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             match-set china src tcp dpts:tcpmux:65535
ACCEPT     udp  --  anywhere             anywhere             match-set china src udp dpts:1:65535
ACCEPT     udp  --  anywhere             anywhere             udp dpts:16384:32768
ACCEPT     all  --  127.0.0.1            anywhere  
ACCEPT     all  --  10.0.0.0/8           anywhere  
ACCEPT     all  --  172.18.0.0/16        anywhere 
ACCEPT     all  --  192.168.0.0/16       anywhere           
ACCEPT     icmp --  anywhere             anywhere            
ACCEPT     all  --  anywhere             anywhere            
Chain FORWARD (policy DROP)
target     prot opt source               destination         
Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     all  --  anywhere             anywhere     

5. 我们需要将数据持久化到 /etc/ipset.conf 这个文件中。

ipset save china > /etc/ipset.conf
ipset restore < /etc/ipset.conf

让服务器重启时,通过脚本在加载 /etc/ipset.conf 中的数据。

chmod +x /etc/rc.d/rc.local
echo "ipset restore < /etc/ipset.conf" >> /etc/rc.d/rc.local

6. 持久化Iptables规则

让服务器重启时,通过脚本在加载 /etc/sysconfig/iptables 中的数据。

# iptables-save > /etc/sysconfig/iptables  # 持久化Iptables规则 好像重启无此文件

# echo "/usr/sbin/iptables-restore < /etc/sysconfig/iptables" >> /etc/rc.d/rc.local

chmod +x /etc/rc.d/rc.local
echo "/usr/sbin/iptables-restore < /root/iptabls.rule" >> /etc/rc.d/rc.local