iptables - Clear all PREROUTING rules with a specific destination address

I have a script that adds iptable PREROUTING rules. They all have the same to address. When I run this:

 iptables --list PREROUTING -t nat

I see output like this:

 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

It seems like I should be able to drop all these rules by writing a command like this...

"drop all PREROUTING rules that go to 192.168.2.1:443"

So, in looking at the options for itables it looks like I need to use the -D option. But I don't know the rulenum to give it. :-(

So, I probably need to query for existing rules, grep to limit it to destination 192.168.2.1:443, and run -D passing the rulenum for each one. I have no idea how to do that. Any help would be appreciated.

Thanks!

EV


Solution 1:

Something like this:

#!/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

You may need to adjust the field number in awk if it's not matching.

Solution 2:

You may be able to simplify the line reversal with 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