一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

linux中IPTABLES常用的例子

时间:2016-03-14 编辑:简简单单 来源:一聚教程网

1.安装iptables

很多Linux已经默认安装iptables,可使用后文的查看命令测试是否安装
CentOS/RedHat下执行:

yum install iptablesDebian/Ubuntu下执行:

apt-get install iptables

iptables –F

例子

#删除已经存在的规则

iptables -P INPUT DROP
#配置默认的拒绝规则。基本规则是:先拒绝所有的服务,然后根据需要再添加新的规则。

iptables -A INPUT -p tcp --dport 80 -j ACCEPT
#打开WEB服务端口的tcp协议

iptables -A INPUT -p tcp --dport 110 -j ACCEPT
#打开POP3服务端口的tcp协议

iptables -A INPUT -p tcp --dport 25 -j ACCEPT
#打开SMTP服务端口的tcp协议

iptables -A INPUT -p tcp --dport 21 -j ACCEPT
#打开FTP服务端口的tcp协议

iptables -A INPUT -p tcp -s 202.106.12.130 --dport 22 -j ACCEPT
#允许IP地址为202.106.12.130这台主机连接本地的SSH服务端口

iptables -A INPUT -p tcp --dport 53 -j ACCEPT
#允许DNS服务端口的tcp数据包流入

iptables -A INPUT -p udp --dport 53 -j ACCEPT
#允许DNS服务端口的udp数据包流入

iptables -A INPUT -p icmp -icmp-type echo-request -i eth1 -j DROP
#防止死亡之ping,从接口eth1进入的icmp协议的请求全部丢弃。

iptables -A FORWARD -p tcp --syn -m limit --limit 1/s -j ACCEPT
#防止SYN Flood (拒绝服务攻击)

iptables -t nat -A POSTROUTING -o eth1 -s 192.168.0.226 -j MASQUERADE
#允许 192.168.0.226通过eth1 IP伪装出外网

iptables -t nat -A POSTROUTING -o eth0 -s 192.168.0.4 -p tcp --dport 25 -j MASQUERADE
#允许 192.168.0.4通过eth0 伪装访问外网的 25端口

6.设置开机启动

一般在安装iptables完成后,开机启动会自动设置成功,但在个别CentOS系统上,貌似还有些问题,可以使用如下命令手动设置
chkconfig --level 345 iptables on

7.保存iptables规则

service iptables save

8.iptables在手动防CC攻击中的简单应用

关于获取攻击者ip的方法,可以通过很多方法获取,如查看网站日志等,本文不再赘述。
a).建立要屏蔽的ip/ip段文件,名为ip.txt

#屏蔽的ip
123.4.5.6
#屏蔽的ip段(编写方法,同前文)
123.4.5.6/24b).建立block_ip.sh脚本文件

复制代码代码如下:

#!/bin/sh
# Filename: block_ip.sh
# Purpose: blocks all IP address/network found in a text file
# The text file must have one IP address or network per line
#################################################################
# Change the following path/filename to match yours
IP_LIST_FILE=/path/to/ip.txt
#################################################################
# Don't change anything below unless you are a smarty pant!
#################################################################
IPTABLES_BIN=/sbin/iptables
# Get the IP address/network from the file and ignore any line starting with # (comments)
BAD_IP_ADDR_LIST=$(grep -Ev "^#" $IP_LIST_FILE)
# Now loop through the IP address/network list and ban them using iptabels
for i in $BAD_IP_ADDR_LIST
do
echo -n "Blocking $i ...";
$IPTABLES_BIN -A INPUT -s $i -j DROP
$IPTABLES_BIN -A OUTPUT -d $i -j DROP
echo "DONE.";
done
##################################################################
# END OF SCRIPT - NOTHING TO SEE HERE - THAT'S ALL FOLKS!
##################################################################

c).运行脚本

sh /path/to/block_ip.sh

热门栏目