I would like to remove some NAT POSTROUTING rules in an automated fashion based on the source or destination IP address.
I know the source and destination IP but I don't necessarily know which policies are already there.
For example, I may have this:
-A POSTROUTING -s 10.10.10.10/32 -p tcp -m tcp --dport 80 -j SNAT --to-source 1.2.3.4
-A POSTROUTING -s 10.10.10.10/32 -p tcp -m tcp --dport 443 -j SNAT --to-source 1.2.3.4
-A POSTROUTING -s 10.10.10.10/32 -j ACCEPT
or I may just have this:
-A POSTROUTING -s 10.10.10.10/32 -j SNAT --to-source 1.2.3.4
I want to unassign that NAT address from the old computer and assign it to a new computer. This is all automated so I can't manually look for it.
What's the best way to remove the old polices for just that IP? Could I use a list + grep command? I normally hang out in the Windows world so I'm not sure the best way to handle this here.
You can match a rule for deletion by specifying it precisely and using
-D
(--delete
) instead of-A
. For instance:To script this, matching a specific IP address, and not losing any rules due to race conditions, let's try something like this. This will delete any rule in the nat table containing a given IP address:
Some notes on this: We use
grep -w
to ensure that IP addresses match exactly, and e.g. a given address that ends in25
doesn't match250
. The transform from-A
to-D
is done bysed
in the loop. And we usexargs
to expand each rule into parameters.iptables -t nat -L POSTROUTING -n --line-numbers | grep -w 1.2.3.4 | awk '{print $1}'
That would grep IP that you want and grab the line number of the firewall rule. Then use
iptables -t nat -D POSTROUTING 1
to delete rule 1, or whatever number you want.