iptables - 清除具有特定目标地址的所有 PREROUTING 规则

use*_*971 5 bash iptables grep

我有一个添加 iptable PREROUTING 规则的脚本。他们都有同样的问题要解决。当我运行这个:

 iptables --list PREROUTING -t nat
Run Code Online (Sandbox Code Playgroud)

我看到这样的输出:

 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
Run Code Online (Sandbox Code Playgroud)

似乎我应该能够通过编写这样的命令来删除所有这些规则......

"drop all PREROUTING rules that go to 192.168.2.1:443"
Run Code Online (Sandbox Code Playgroud)

因此,在查看 itables 的选项时,我似乎需要使用 -D 选项。但我不知道给出它的规则。:-(

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

谢谢!

电动汽车

bah*_*mat 3

像这样的东西:

#!/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
Run Code Online (Sandbox Code Playgroud)

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