首页·终端命令

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