我有一个添加 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"
因此,在查看 itables 的选项时,我似乎需要使用 -D 选项。但我不知道该给它什么规则。:-(
因此,我可能需要查询现有规则,使用 grep 将其限制为目标 192.168.2.1:443,然后运行 -D 并为每个规则传递规则号。我不知道该怎么做。任何帮助都将不胜感激。
谢谢!
电动汽车
答案1
像这样:
#!/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 中的字段编号。
答案2
您可能能够使用 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
答案3
您可以使用以下一行代码:
sudo iptables -S | grep $pattern | cut -d " " -f 2- | xargs -L1 sudo iptables -D
其中 $pattern 是您想要的模式。
我建议您首先回显此命令的结果,以避免出现问题
答案4
使用--line-numbers
显示规则编号,grep 和 awk 即可。
# iptables -vnL -t nat --line-numbers |grep 10.1.1.0|awk '{print $1}'
1
然后您可以使用它for
来清除与一个特定 IP 匹配的所有规则。
# for rule in $(iptables -vnL -t nat --line-numbers |grep 10.1.1.0|awk '{print $1}'); do iptables -D INPUT $rule; done
请记住这些数字是按表显示的,因此您可能需要按表限制列出命令并逐个清除。