iptables在Linux发行版本如Centos、Debian、Ubuntu、Redhat等的配置内容基本一致,但是配置方式有所不同。由于工作日常用的是Centos 6.x,它的配置较简单。下面对Debian上配置iptables做一个说明。
root@localhost:~# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
Chain FORWARD (policy ACCEPT)
target prot opt source destination
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
root@localhost:~#
INPUT、FORWARD和OUTPUT链中均没有内容,说明此时iptables是空的,没有进行任何配置。
配置iptables
(1)编辑iptables.test.rules,保存其配置
root@localhost:~# vi /etc/iptables.test.rules
# Generated by iptables-save
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
-I INPUT -p tcp --dport 8080 -j ACCEPT
-I INPUT -p udp --dport 8080 -j ACCEPT
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT
# Completed
上述是一个模板,可以根据需求进行修改。如上开放了tcp22端口,以及8888的tcp和udp端口。
(2)加载iptables.test.rules规则,并查看(注意restore单词 原文章中写错了 本文已修改)
root@localhost:/home# iptables-restore < /etc/iptables.test.rules
root@localhost:/home# iptables -L
Chain INPUT (policy ACCEPT)
target prot opt source destination
ACCEPT udp -- anywhere anywhere udp dpt:8080
ACCEPT tcp -- anywhere anywhere tcp dpt:8080
ACCEPT all -- anywhere anywhere state RELATED,ESTABLISHED
ACCEPT icmp -- anywhere anywhere
ACCEPT all -- anywhere anywhere
ACCEPT tcp -- anywhere anywhere state NEW tcp dpt:ssh
REJECT all -- anywhere anywhere reject-with icmp-host-prohibited
Chain FORWARD (policy ACCEPT)
target prot opt source destination
REJECT all -- anywhere anywhere reject-with icmp-host-prohibited
Chain OUTPUT (policy ACCEPT)
target prot opt source destination
root@localhost:/home#
(3)设置开机启动
root@localhost:/home# vi /etc/network/if-pre-up.d/iptables
#!/bin/bash
/sbin/iptables-restore < /etc/iptables.test.rules
root@localhost:/home# chmod +x /etc/network/if-pre-up.d/iptables
(4)重启查看是否开机加载
root@localhost:/home# reboot
root@localhost:~# iptables -L