-
-
Save Ne00n/7a849809f99462601e9265b23bd602ab to your computer and use it in GitHub Desktop.
Update iptables firewall with dynamic DNS updates from cron job
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 | |
# Set as cronjob | |
# * * * * * /root/iptables-ddns.sh >> /var/logs/iptables-ddns.log 2>&1 | |
log () { | |
echo "[$(date "+%F +%T")] [$1] $2" >> "$LOGS/iptables-ddns.log" | |
} | |
HOSTS="mydynamichost.ddns.net" | |
LOGS="/var/logs/" | |
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