iptables – 清除所有PREROUTING规则与特定的目标地址

我有一个脚本添加了iptable PREROUTING规则。 他们都有相同的地址。 当我运行这个:

iptables --list PREROUTING -t nat 

我看到这样的输出:

  DNAT tcp -- anywhere 165.193.122.18 tcp dpt:https to:192.168.2.1:443 DNAT tcp -- anywhere 63.135.91.11 tcp dpt:https to:192.168.2.1:443 DNAT tcp -- anywhere 63.135.90.224 tcp dpt:https to:192.168.2.1:443 

看来我应该可以通过编写像这样的命令来放弃所有这些规则…

 "drop all PREROUTING rules that go to 192.168.2.1:443" 

所以,在看它的选项看起来像我需要使用-D选项。 但是我不知道这个原因。 🙁

所以,我可能需要查询现有的规则,grep将其限制为目标192.168.2.1:443,然后运行-D传递每个规则的rulenum。 我不知道该怎么做。 任何帮助,将不胜感激。

谢谢!

EV

像这样的东西:

 #!/bin/bash for line_num in $(sudo iptables --line-numbers --list PREROUTING -t nat | awk '$7=="to:192.168.2.1:443" {print $1}') do # You can't just delete lines here because the line numbers get reordered # after deletion, which would mean after the first one you're deleting the # wrong line. Instead put them in a reverse ordered list. LINES="$line_num $LINES" done # Delete the lines, last to first. for line in $LINES do sudo iptables -t nat -D PREROUTING $line done unset LINES 

如果不匹配,您可能需要在awk中调整字段号。

您可能可以通过tac简化线路反转:

 #!/bin/bash for line in $(sudo iptables --line-numbers --list PREROUTING -t nat | awk '$7=="to:192.168.2.1:443" {print $1}' | tac) do # You can't just delete lines here because the line numbers get reordered # after deletion, which would mean after the first one you're deleting the # wrong line. Instead put them in a reverse ordered list. sudo iptables -t nat -D PREROUTING $line done 

你可以使用下面的一行代码:

 sudo iptables -S | grep $pattern | cut -d " " -f 2- | xargs -L1 sudo iptables -D 

$ pattern是你想要的模式。

我build议你先回应一下这个命令的结果,以避免戏剧

使用--line-numbers显示规则号,grep和awk它,你有它。

 # iptables -vnL -t nat --line-numbers |grep 10.1.1.0|awk '{print $1}' 1 

然后您可以使用它来清除与特定IP相匹配的所有规则。

 # for rule in $(iptables -vnL -t nat --line-numbers |grep 10.1.1.0|awk '{print $1}'); do iptables -D INPUT $rule; done 

请记住,每个表格都显示这些数字,因此您可能需要按表格限制列表命令并逐个清除。