Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#!/usr/bin/env bash
NGINX_CONF_PATH="/usr/local/nginx/conf/deny-ips.conf"
if ! [ -f "$NGINX_CONF_PATH" ]; then
echo "Error: '$NGINX_CONF_PATH' is not found."
exit 1
fi
SCRIPT_NAME=$(basename $(readlink -f $0))
DEFAULT_NOTES="Added with $SCRIPT_NAME"
usage() {
if [ $# -eq 0 ]; then
echo "USAGE : $SCRIPT_NAME [-r] <IP_ADDRESS> [...NOTES=${DEFAULT_NOTES}]"
echo "EXAMPLE : $SCRIPT_NAME 123.44.55.66 Spam bot"
exit 0
fi
}
reload_nginx() {
echo "Reloading NGINX..."
nginx -s reload
echo "Exited with code ${?}."
}
execute() {
FORMAT="deny ${IP_ADDRESS};"
EXISTS=$(grep "^${FORMAT}" "$NGINX_CONF_PATH")
if [ "$REMOVE" ]; then
if [ "$EXISTS" ]; then
sed -i -r "s/(^${FORMAT} # .*$)/# \1 -- Commented out by ${SCRIPT_NAME}/g" $NGINX_CONF_PATH
echo "Removed '${IP_ADDRESS}' from '${NGINX_CONF_PATH}'."
reload_nginx
else
echo "Error: '${IP_ADDRESS}' is not in '${NGINX_CONF_PATH}'."
exit 1
fi
else
if [ "$EXISTS" ]; then
echo "Error: '${IP_ADDRESS}' is already in '${NGINX_CONF_PATH}'."
exit 1
else
echo "${FORMAT} # ${NOTES}" >> "$NGINX_CONF_PATH"
echo "Added '${IP_ADDRESS}' into '${NGINX_CONF_PATH}' with notes: '${NOTES}'."
reload_nginx
fi
fi
}
while getopts :hr opt; do
case "${opt}" in
h)
usage
exit 0 ;;
r)
REMOVE=true
esac
done
shift $(($OPTIND - 1))
IP_ADDRESS="$1"; shift
NOTES="$@"
if [ -z "$IP_ADDRESS" ]; then
usage
exit 1
fi
if [ -z "$NOTES" ]; then
NOTES=$DEFAULT_NOTES
fi
execute
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment