Linux下iptables 禁止端口和开放端口示例

2019-10-10 14:00:18王旭

hostwww.google.com  

输入这个命令后,一直等待,说明DNS不通

出现下面提示 :;; connection timed out; no servers could be reached

ping 一下域名也是不通

[root@localhost ~]#pingwww.google.com
ping: unknown hostwww.google.com

我这里的原因就是 iptables 限制了53端口。

有些服务器,特别是Web服务器减慢,DNS其实也有关系的,无法发送包到DNS服务器导致的。

下面演示下如何使用 iptables 来设置DNS 53这个端口,如果你不知道 域名服务端口号,你

可以用命令 :

grep domain /etc/services
[root@localhost] ~ #grep domain /etc/services
domain     53/tcp             # name-domain server
domain     53/udp
domaintime   9909/tcp            # domaintime
domaintime   9909/udp            # domaintime

看到了吧, 我们一般使用 udp 协议。

好了, 开始设置。。。

iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

这是我们 ping 一个域名,数据就是从本机出去,所以我们先设置 OUTPUT,

我们按照ping这个流程来设置。

然后 DNS 服务器收到我们发出去的包,就回应一个回来

iptables -A INPUT -p udp --sport 53 -j ACCEPT

同时还要设置

iptables -A INPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p udp --sport 53 -j ACCEPT

好了, 下面开始测试下, 可以用 iptables -L -n 查看设置情况,确定没有问题就可以测试了

[root@localhost ~iptables -L -n
Chain INPUT (policy DROP)
target   prot opt source        destination
ACCEPT   tcp -- 0.0.0.0/0      0.0.0.0/0      tcp dpt:22
ACCEPT   tcp -- 0.0.0.0/0      0.0.0.0/0      tcp dpt:80
ACCEPT   udp -- 0.0.0.0/0      0.0.0.0/0      udp spt:53
ACCEPT   udp -- 0.0.0.0/0      0.0.0.0/0      udp dpt:53

Chain FORWARD (policy DROP)
target   prot opt source        destination

Chain OUTPUT (policy DROP)
target   prot opt source        destination
ACCEPT   tcp -- 0.0.0.0/0      0.0.0.0/0      tcp spt:22 state ESTABLISHED
ACCEPT   tcp -- 0.0.0.0/0      0.0.0.0/0      tcp spt:80 state ESTABLISHED
ACCEPT   udp -- 0.0.0.0/0      0.0.0.0/0      udp dpt:53
ACCEPT   udp -- 0.0.0.0/0      0.0.0.0/0      udp spt:53

可以测试一下 是否 DNS 可以通过iptables 了。

[root@localhost ~]#hostwww.google.com
www.google.comis an alias forwww.l.google.com.
www.l.google.comis an alias for www-china.l.google.com.
www-china.l.google.com has address 64.233.189.104
www-china.l.google.com has address 64.233.189.147
www-china.l.google.com has address 64.233.189.99

正常可以解析 google 域名。

ping 方面可能还要设置些东西。

用 nslookup 看看吧


[root@localhost ~]#nslookup >www.google.com Server: 192.168.1.1 Address: 192.168.1.1#53 Non-authoritative answer: www.google.comcanonical name =www.l.google.com. www.l.google.com canonical name = www-china.l.google.com. Name: www-china.l.google.com Address: 64.233.189.147 Name: www-china.l.google.com Address: 64.233.189.99 Name: www-china.l.google.com Address: 64.233.189.104