从 bash 脚本中删除所有 DROP iptables 规则

Remove all DROP iptables rules from bash script

我想从 bash 脚本中删除所有 iptables DROP 规则。 这是我的脚本:

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

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

但输出是:

[*] 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.

为什么?

如果我运行手动命令:

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

有效。

谢谢,BuDuS。

在您的脚本中,在执行 iptables 时,您的 IFS 仍设置为换行符。因此 bash 无法对您的命令参数进行分词。

一旦不再需要修改后的值,我会立即返回 IFS=$IFS_OLD,这可能是在赋值给 rule_list.

之后