IPTables – Using XARGS Commands in Shell Script Without Terminal

iptablesopenvpnxargs

I am trying to configure an iptables rule that finds a matching IP and deletes as many instances it finds in a one liner. I have the command and it works in a traditional shell environment with path variables.

This one is running without a shell terminal, its part of an openvpn client-disconnect script. I have a working solution using the following commands to fine –line-number, sort in reverse then delete each line in a loop. Problem is dynamic nature of the IPtables rules can lead to accidentally deleting the wrong line.

Working:
sudo -tt /sbin/iptables -t mangle -w -n -L –line-numbers | grep -w "$ifconfig_pool_remote_ip" | awk '{print $1}' | sort -nr

for i in $IPTABLES_RULEID ; do
        echo "================= Removing IPv4 Mangle Rule ID $i ===================="
        sudo -tt /sbin/iptables -w -t mangle -D PREROUTING $i
done

Here is what i'm trying to replace it with:

sudo -tt /sbin/iptables -t mangle -S PREROUTING | /usr/bin/grep -w "$ifconfig_pool_remote_ip" | sed 's/^-A //g' | /usr/bin/xargs -rL1 /sbin/iptables -t mangle -D

The error indicates its not parsing all the command line options

Jan 5 00:55:10 vpn1-udp-de openvpn[1240]: iptables v1.8.4 (nf_tables): Couldn't load match set':No such file or directory Jan 5 00:55:10 vpn1-udp-de openvpn[1240]: Try iptables -h' or 'iptables –help' for more information.
Jan 5 00:55:10 vpn1-udp-de openvpn[1240]: iptables v1.8.4 (nf_tables): unknown option "–on-port"
Jan 5 00:55:10 vpn1-udp-de openvpn[1240]: Try `iptables -h' or 'iptables –help' for more information.

ref:

/sbin/iptables -t mangle -S PREROUTING | grep -w 10.13.0.6
-A PREROUTING -s 10.13.0.6/32 -p udp -m set --match-set portsudp dst -j TPROXY --on-port 41201 --on-ip 127.0.0.1 --tproxy-mark 0x1/0x1
-A PREROUTING -s 10.13.0.6/32 -p tcp -j TPROXY --on-port 41201 --on-ip 127.0.0.1 --tproxy-mark 0x1/0x1

Best Answer

I wonder if something like this might work better

sudo /sbin/iptables -t mangle -S PREROUTING |
/usr/bin/grep -w "$ifconfig_pool_remote_ip" |
sed 's/^-A /iptables -t mangle -D /g' |
sudo /bin/sh -ex
# the -x is just there to echo the commands for debugging.