Skip to content

Instantly share code, notes, and snippets.

@evaristorivi
Created June 29, 2020 13:08
Show Gist options
  • Save evaristorivi/5544a815b73f93e7b52cb82d2929ba9a to your computer and use it in GitHub Desktop.
Save evaristorivi/5544a815b73f93e7b52cb82d2929ba9a to your computer and use it in GitHub Desktop.
#!/bin/bash
function valid_ip()
{
local ip=$1
local stat=1
if [[ $ip =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
ip=($ip)
IFS=$OIFS
[[ ${ip[0]} -le 255 && ${ip[1]} -le 255 \
&& ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]
stat=$?
fi
return $stat
}
HOSTNAME=YOUR.DNS.NAME.HERE
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
new_ip=$(host $HOSTNAME | head -n1 | cut -f4 -d ' ')
old_ip=$(/usr/sbin/ufw status | grep $HOSTNAME | head -n1 | tr -s ' ' | cut -f3 -d ' ')
if ! valid_ip $new_ip;
then
exit 1
fi
if [ "$new_ip" = "$old_ip" ] ; then
exit 0
else
if [ -n "$old_ip" ] ; then
/usr/sbin/ufw delete allow from $old_ip to any port 22,6556 proto tcp
fi
/usr/sbin/ufw allow from $new_ip to any port 22,6556 proto tcp comment $HOSTNAME
echo "Se ha modificado iptables por cambio de ip $new_ip"
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment