iptables:从文件和阻止中读取IP地址列表
时间:2020-01-09 10:41:05 来源:igfitidea点击:
如何使用文本文件读取IP地址(子网)列表,并使用Linux iptables命令阻止所有这些地址?
您可以创建一个文件,其中包含每行所有被阻止的IP地址或子网的列表。
您可以使用while循环逐行读取文件。
示例:iptables从文本文件中读取IP /子网
创建文本文件/root/firewall/badips.db,如下所示:
# Block db # Added on Aug/19/2009 192.54.1.2 # Spammers 203.1.2.3/29
读取文本文件的基本逻辑如下:
_input=/path/to/text.db IPT=/sbin/iptables $IPT -N droplist egrep -v "^#|^$" x | while IFS= read -r ip do $IPT -A droplist -i eth1 -s $ip -j LOG --log-prefix " myBad IP BlockList " $IPT -A droplist -i eth1 -s $ip -j DROP done < "$_input" # Drop it $IPT -I INPUT -j droplist $IPT -I OUTPUT -j droplist $IPT -I FORWARD -j droplist
这是一个示例shell脚本:
#!/bin/bash
# Modify script as per your setup
# Usage: Sample firewall script
# --------------------------
_input=/root/firewall/badips.db
_pub_if="eth1"
IPT=/sbin/iptables
# Die if file not found
[ ! -f "$_input" ] && { echo "##代码##: File $_input not found."; exit 1; }
# DROP and close everything
$IPT -P INPUT DROP
$IPT -P OUTPUT DROP
$IPT -P FORWARD DROP
# Unlimited lo access
$IPT -A INPUT -i lo -j ACCEPT
$IPT -A OUTPUT -o lo -j ACCEPT
# Allow all outgoing connection but no incoming stuff by default
$IPT -A OUTPUT -o ${_pub_if} -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
$IPT -A INPUT -i ${_pub_if} -m state --state ESTABLISHED,RELATED -j ACCEPT
### Setup our black list ###
# Create a new chain
$IPT -N droplist
# Filter out comments and blank lines
# store each ip or subnet in $ip
egrep -v "^#|^$" x | while IFS= read -r ip
do
# Append everything to droplist
$IPT -A droplist -i ${_pub_if} -s $ip -j LOG --log-prefix " Drop Bad IP List "
$IPT -A droplist -i ${_pub_if} -s $ip -j DROP
done <"${_input}"
# Finally, insert or append our black list
$IPT -I INPUT -j droplist
$IPT -I OUTPUT -j droplist
$IPT -I FORWARD -j droplist
# Okay add your rest of $IPT commands here
# Example: open port 53
#$IPT -A INPUT -i ${_pub_if} -s 0/0 -d 1.2.3.4 -p udp --dport 53 -j ACCEPT
#$IPT -A INPUT -i ${_pub_if} -s 0/0 -d 1.2.3.4 -p tcp --dport 53 -j ACCEPT
# Open port 80
# $IPT -A INPUT -i ${_pub_if} -s 0/0 -d 1.2.3.4 -p tcp --destination-port 80 -j ACCEPT
# Allow incoming ICMP ping pong stuff
# $IPT -A INPUT -i ${_pub_if} -p icmp --icmp-type 8 -m state --state NEW,ESTABLISHED,RELATED -m limit --limit 30/sec -j ACCEPT
# $IPT -A INPUT -i ${_pub_if} -p icmp -m icmp --icmp-type 3 -m limit --limit 30/sec -j ACCEPT
# $IPT -A INPUT -i ${_pub_if} -p icmp -m icmp --icmp-type 5 -m limit --limit 30/sec -j ACCEPT
# $IPT -A INPUT -i ${_pub_if} -p icmp -m icmp --icmp-type 11 -m limit --limit 30/sec -j ACCEPT
# drop and log everything else
$IPT -A INPUT -m limit --limit 5/m --limit-burst 7 -j LOG
$IPT -A INPUT -j DROP

