Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

iptables 規則的查看、新增、刪除與修改

一、查看規則

iptables -nvL --line-number

參數說明:-L 列出目前表的所有規則,預設是 filter 表,要看 NAT 表加上 -t NAT;-n 不做 IP 反查,顯示速度快很多;-v 輸出詳細資訊,包含通過該規則的封包數、總位元組數與網路介面;--line-number 顯示規則序號,刪除與修改時必用。

二、新增規則

新增有兩個參數:-A 附加到規則鏈尾端,-I 插入到指定位置(不指定則插入首位)。

[root@test ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 DROP all -- 192.168.1.1 0.0.0.0/0
2 DROP all -- 192.168.1.2 0.0.0.0/0
3 DROP all -- 192.168.1.4 0.0.0.0/0

[root@test ~]# iptables -A INPUT -s 192.168.1.5 -j DROP      # 附加到尾端
[root@test ~]# iptables -I INPUT 3 -s 192.168.1.3 -j DROP     # 插入第三行

再查一次就會看到 192.168.1.3 落在第三行,原本的 192.168.1.4 往後遞補成第四行。

三、刪除規則

刪除用 -D。可以直接重寫整條規則:

[root@test ~]# iptables -D INPUT -s 192.168.1.5 -j DROP

但規則很長時,重打一遍既浪費時間又容易出錯。實務上更常用序號刪除:

[root@test ~]# iptables -nL --line-number    # 先找出序號
[root@test ~]# iptables -D INPUT 2           # 刪除第二行

四、修改規則

修改用 -R,同樣以序號定位:

[root@test ~]# iptables -nL --line-number
Chain INPUT (policy ACCEPT)
num target prot opt source destination
1 DROP all -- 192.168.1.1 0.0.0.0/0
2 DROP all -- 192.168.1.2 0.0.0.0/0
3 DROP all -- 192.168.1.5 0.0.0.0/0

[root@test ~]# iptables -R INPUT 3 -j ACCEPT

再查一次,第三條的 target 已從 DROP 變成 ACCEPT。

小提醒:以上改動都是即時生效、重開機後消失的。要永久保留,需存檔(如 CentOS 的 service iptables save)或改用 iptables-persistent 一類的工具。

Copyright © Linux教程網 All Rights Reserved