Created
February 13, 2013 14:50
-
-
Save mrklein/4945083 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
CHAIN=SELFCONTROL | |
IPTABLES=/sbin/iptables | |
IP_PATTERN='/^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$/p' | |
usage() { | |
echo "Usage: $0 <IP address or hostname>" | |
exit 1 | |
} | |
ban() { | |
local retval=0 | |
e=$($IPTABLES -I $CHAIN -s $1 -j REJECT) | |
if [ "X$e" != "X" ]; then | |
retval=1 | |
fi | |
e=$($IPTABLES -I $CHAIN -d $1 -j REJECT) | |
if [ "X$e" != "X" ]; then | |
retval=1 | |
fi | |
return $retval | |
} | |
is_ip() { | |
[[ "X$(echo $1 | sed -n $IP_PATTERN)" != "X" ]] && return 0 || return 1 | |
} | |
chain_exists() { | |
$IPTABLES -n -L $CHAIN > /dev/null 2>&1 | |
} | |
create_chain() { | |
$IPTABLES -N $CHAIN | |
$IPTABLES -I OUTPUT -j $CHAIN | |
$IPTABLES -I $CHAIN -j RETURN | |
} | |
[[ $# -eq 0 ]] && usage | |
chain_exists || create_chain | |
for arg in $@; do | |
echo -n "Banning: $arg ... " | |
if ( is_ip $arg ); then | |
ban "$arg" | |
else | |
echo | |
for ip in $(dig $arg +short); do | |
if ( is_ip $ip ); then | |
echo -n " -> $ip " | |
if ( ban $ip ); then | |
echo "OK" | |
else | |
echo "Fail" | |
fi | |
fi | |
done | |
fi | |
echo "done." | |
done | |
service iptables save |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment