Search code examples
linuxbashiptables

Remove all DROP iptables rules from bash script


I want to delete all iptables DROP rules from a bash script. This is my script:

#!/bin/bash

# Remove all DROPs.

######################################################################
#_____________________________________________________________________
iptables="/sbin/iptables"

######################################################################
#_____________________________________________________________________
echo "[*] Removing all DROPs ..."
IFS_OLD=$IFS
IFS=$'\n'
rule_list=$(${iptables} -S | grep 'DROP$')
for drop_rule in ${rule_list}; do
    undrop_rule=$(printf -- "${drop_rule}\n" | sed 's@^-A@-D@')
    printf "[-] ${iptables} ${undrop_rule}\n"

    ${iptables} -v ${undrop_rule}
    [ $? == 1 ] && echo "[E] Unable to delete DROP rule." && exit 1
done
IFS=$IFS_OLD

######################################################################
#_____________________________________________________________________
printf '\n\n'
${iptables} -S

######################################################################
#_____________________________________________________________________

But the output is:

[*] Removing all DROPs ...
[-] /sbin/iptables -D INPUT -s 209.126.1.2/32 -i eth0 -j DROP
  all opt -- in * out *  0.0.0.0/0  -> 0.0.0.0/0
iptables: Bad rule (does a matching rule exist in that chain?).
[E] Unable to delete DROP rule.

Why ?

If I run manually the command:

/sbin/iptables -D INPUT -s 209.126.1.2/32 -i eth0 -j DROP

it work.

Thanks, BuDuS.


Solution

  • In your script, your IFS is still set to a newline by the time the iptables is executed. Hence bash can't word-split your command arguments.

    I would set back IFS=$IFS_OLD as soon as the modified value is not needed anymore, which is probably after the assignement to rule_list.