首頁·終端機命令

iptables

網路

用法

sudo iptables -L -n -v --line-numbers

修改正在生效的封包過濾規則;規則自上而下比對、先命中者勝,所以附加在 ACCEPT 之後的 DROP 永遠不會生效,不儲存的話重開機就沒了,而在放通 22 埠之前把預設政策設成 DROP,會把你自己關在遠端機器外面。

常用選項

選項含義
-L -n -v --line-numbersList the rules with counters and the numbers you need for -D.
-A <CHAIN>Append to the end of a chain, where an earlier rule may already have decided.
-I <CHAIN> 1Insert at the top, which is usually what you meant.
-D <CHAIN> <n>Delete rule number n.
-p tcp --dport 22Match protocol and destination port.
-s 10.0.0.0/8Match a source address or range.
-j ACCEPT|DROP|REJECTWhat to do with a matching packet.
-P <CHAIN> DROPSet the default policy, applied when no rule matched.

範例

sudo iptables -L -n -v --line-numbers

Read the current rules before changing anything.

sudo iptables -I INPUT 1 -p tcp --dport 22 -j ACCEPT

Guarantee your own SSH access first.

sudo iptables-save > /etc/iptables/rules.v4

Make the rules survive a reboot.

連不上的時候,這些能把範圍縮小——是名稱解析不了、沒有路由,還是連接埠被擋。

怎麼看

  • 方括號 [ ] 表示這部分可以不寫。
  • 省略號 … 表示可以寫多個。
  • 選項區分大小寫——有些命令裡 -r 和 -R 不是一回事。

常見問題

Q. iptables 是做什麼的?

修改正在生效的封包過濾規則;規則自上而下比對、先命中者勝,所以附加在 ACCEPT 之後的 DROP 永遠不會生效,不儲存的話重開機就沒了,而在放通 22 埠之前把預設政策設成 DROP,會把你自己關在遠端機器外面。

Q. 怎麼寫?

sudo iptables -L -n -v --line-numbers —— 方括號表示可以省略的部分。

Q. 值得記的選項有幾個?

這裡列了 8 個,完整列表在 man iptables。這條命令屬於網路。

相關命令

man 手冊: man iptables