一个屏蔽 IP 的脚本

在测试可用性的时候,经常需要模拟断网。这时候用 iptables 是比较方便的。但是如果想更方便一点,不用去敲那么长的命令会更好些。于是就写了个 ban_ip 脚本。

#!/bin/bash

if [[ "$EUID" != 0 ]]; then
  echo "should run as root"
  exit 1
fi

action="DROP"
comment="ban_ip"
cmd="$1"
case "$cmd" in
list)
  iptables -L -n | awk -v "cmt=$comment" '$0~cmt{print $4}'
  ;;
add)
  ip="$2"
  if [[ -z "$ip" ]]; then
    echo "missing arg ip"
    exit 1
  fi
  iptables -A INPUT -s "$ip" -j "$action" -m comment --comment "$comment"
  ;;
del)
  ip="$2"
  if [[ -z "$ip" ]]; then
    echo "missing arg ip"
    exit 1
  fi
  iptables -D INPUT -s "$ip" -j "$action" -m comment --comment "$comment"
  ;;
*)
  echo "bad command: should be list, add <ip>, del <ip>"
  exit 1
  ;;
esac

用的时候就方便了不少,也便于查看当前已经 ban 掉的 ip。

$ sudo ./ban_ip.sh list
10.10.10.1

$ sudo ./ban_ip.sh add 10.10.10.2

$ sudo ./ban_ip.sh list
10.10.10.1
10.10.10.2

$ sudo ./ban_ip.sh del 10.10.10.1

$ sudo ./ban_ip.sh list
10.10.10.2

Leave a Reply

Your email address will not be published. Required fields are marked *