bash – 检查iptables用户链是否存在的最佳方法.

前端之家收集整理的这篇文章主要介绍了bash – 检查iptables用户链是否存在的最佳方法.前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图以编程方式创建用户链并在iptables中删除它们.我想知道检查用户链是否存在以及是否创建用户链的最佳方法是什么.
使用iptables(8)列出链,将stdout / stderr重定向到/ dev / null,并检查退出代码.如果链存在,iptables将退出true.

这个shell函数来自我的iptables前端脚本:

  1. chain_exists()
  2. {
  3. [ $# -lt 1 -o $# -gt 2 ] && {
  4. echo "Usage: chain_exists <chain_name> [table]" >&2
  5. return 1
  6. }
  7. local chain_name="$1" ; shift
  8. [ $# -eq 1 ] && local table="--table $1"
  9. iptables $table -n --list "$chain_name" >/dev/null 2>&1
  10. }

请注意,我使用-n选项,以便iptables不会尝试将IP地址解析为主机名.没有这个,你会发现这个功能会很慢.

然后,您可以使用此函数有条件地创建链:

  1. chain_exists foo || create_chain foo ...

其中create_chain是另一个创建链的函数.您可以直接调用iptables,但上面的命名使得它显而易见.

猜你在找的Bash相关文章