Iptables remove specific rules by comment

我与影子孤独终老i 提交于 2019-12-10 11:02:01

问题


I need to delete some rules with same comment.

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'

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

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

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


回答1:


You can use the following command:

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

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"
...

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.


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




回答2:


Yet another way to Remove by comment:

NOWRULES=$(iptables --line-number -nL INPUT | grep comment_here | awk '{print $1}' | tac)
for rul in $NOWRULES; do     /sbin/iptables -D INPUT $rul; sleep 0.1; done


来源:https://stackoverflow.com/questions/29058501/iptables-remove-specific-rules-by-comment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!