Skip to content

Instantly share code, notes, and snippets.

@lattice0
Last active April 25, 2018 02:34
Show Gist options
  • Save lattice0/3d629e5168ff8901b02af8225483dbe1 to your computer and use it in GitHub Desktop.
Save lattice0/3d629e5168ff8901b02af8225483dbe1 to your computer and use it in GitHub Desktop.
ufw rule for dynamic host. Usage
#!/bin/bash
HOSTNAME=dynamichost.domain.com
LOGFILE=$HOME/ufw$HOSTNAME.log
Current_IP=$(host $HOSTNAME | head -n1 | cut -f4 -d ' ')
if [ ! -f $LOGFILE ]; then
/usr/sbin/ufw allow from $Current_IP to any port 22 proto tcp
/usr/sbin/ufw allow from any to $Current_IP port 22 proto tcp
echo $Current_IP > $LOGFILE
else
Old_IP=$(cat $LOGFILE)
if [ "$Current_IP" = "$Old_IP" ] ; then
echo IP address has not changed
else
/usr/sbin/ufw delete allow from $Old_IP to any port 22 proto tcp
/usr/sbin/ufw delete allow from any to $Old_IP port 22 proto tcp
/usr/sbin/ufw allow from $Current_IP to any port 22 proto tcp
/usr/sbin/ufw allow from any to $Current_IP port 22 proto tcp
echo $Current_IP > $LOGFILE
echo iptables have been updated
fi
fi
#Usage:
#sudo contrab -e
#*/30 * * * * /bin/sh /home/lz/script.sh
#If you run the first time not as root it'll produce the logfile, so in the nxt time as root it'll say that ip didn't change and do nothing. Run first time as user. Delete log file if you did this mistake.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment