iptables通过评论删除特定规则 [英] Iptables remove specific rules by comment

查看:111
本文介绍了iptables通过评论删除特定规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要删除一些带有相同注释的规则.

I need to delete some rules with same comment.

例如,我有一条带有comment ="test it"的规则,因此我可以像这样获得它们的列表:

For example I have rules with comment = "test it", so i can get list of them like this:

sudo iptables -t nat -L | grep 'test it'

但是我如何删除带有注释"test it"的所有PREROUTING规则?

But how can i delete all PREROUTING rules with comment 'test it'?

UPD: 正如@ hek2mgl所说,我可以做这样的事情:

UPD: As @hek2mgl said, i can do something like this:

sudo bash -c "iptables-save > iptables.backup"
sed -i '/PREROUTING.*--comment.* "test it"/d' iptables.backup
sudo iptables-restore < iptables.backup
sudo rm iptables.backup

但是在保存和还原之间可能会更改iptables,因此还原后将出现问题=/

But between save and restore could be changes in iptables, so after restore there will be problems =/

推荐答案

您可以使用以下命令:

iptables-save | sed -r '/PREROUTING.*comment.*test it/s/-A/iptables -D/e'

iptables-save将返回iptables命令,可以执行该命令以在重新启动或执行任何操作后返回防火墙的当前状态.

iptables-save will return iptables commands that can be executed to return the current state of the firewall after a reboot or whatever.

其含义将包含类似以下内容的行:

Meaning it will contain lines like:

...
-A PREROUTING -p tcp -m tcp --dport 25 -j ACCEPT -m comment --comment "test it"
...

sed命令搜索包含PREROUTING.*comment.*test it的行(应该足够好),并在术语iptables plus之前加上-D代替-A,因为-D会删除规则.然后使用e命令执行替换操作的结果get. e命令是sed的GNU扩展.

The sed command searches for lines containing PREROUTING.*comment.*test it (should be good enough) and prepends the term iptablesplus replaces -A by -D since -D deletes a rule. The result of the replacement operation get's then executed using the e command. The e command is a GNU extension to sed.

注意:如果除了要执行命令之外,还想打印命令,可以使用s/-A/iptables -D/pe.

Note: If you want to print the command in addition to simply executing it you can use s/-A/iptables -D/pe.

这篇关于iptables通过评论删除特定规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆