Skip to content

Instantly share code, notes, and snippets.

@anderson-marques
Forked from eusonlito/iptables-ddns.sh
Created February 9, 2022 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anderson-marques/4519d5141c9e64efecb27d46aaaa8e53 to your computer and use it in GitHub Desktop.
Save anderson-marques/4519d5141c9e64efecb27d46aaaa8e53 to your computer and use it in GitHub Desktop.
Update iptables firewall with dynamic DNS updates from cron job
#!/bin/bash
# Set as cronjob
# * * * * * /root/scripts/iptables-ddns.sh >> /root/logs/iptables-ddns.log 2>&1
log () {
echo "[$(date "+%F +%T")] [$1] $2" >> "$LOGS/changes.log"
}
HOSTS="mydynamichost.ddns.net"
LOGS="/root/logs/iptables-ddns/"
PORT=22
if [ ! -d "$LOGS" ]; then
install -d "$LOGS"
fi
for host in $HOSTS; do
LOG="$LOGS/$host"
CURRENT=$(getent hosts "$host" | awk '{print $1}')
if [ "$CURRENT" == "" ]; then
log "$host" "[EMPTY] Current address empty"
continue
fi
if [ -f "$LOG" ]; then
PREVIOUS=$(cat "$LOG")
else
PREVIOUS=""
fi
if [ "$CURRENT" == "$PREVIOUS" ]; then
log "$host" "[SAME] Current and Previous are same ($CURRENT)"
continue
fi
if [ "$PREVIOUS" != "" ]; then
iptables -D INPUT -s "$PREVIOUS" -p tcp -m tcp --dport "$PORT" -j ACCEPT
fi
iptables -A INPUT -s "$CURRENT" -p tcp -m tcp --dport "$PORT" -j ACCEPT
echo "$CURRENT" > $LOG
log "$host" "[UPDATED] $PREVIOUS > $CURRENT"
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment