Script to Add Dynamic IP to /etc/hosts

I have a dynamic IP from my internet service provider and sometimes it takes longer to SSH to my server as it needs to resolve the address. On static IP, I can put the address into public DNS server to a quick resolving process,  but as it uses dynamic IP, I would need to use a different approach.

As I have dynamic DNS from Synology (can also work with other DDNS provider), a little bash script below can help me to automatically add IP on an interval basis, replace the selected predefined row on /etc/hosts.
Script :
[code lang=”bash”]
ip=`nslookup | grep -i addr | grep -v “#” | cut -d “:” -f2 | sed -e ‘s/^[[:space:]]*//’`
if grep -q $ip $FILE;
echo “Ignore, IP has been previously added”
echo “$ip” >> /etc/hosts
echo “$ip has been added to /etc/hosts”
#echo “IP:$ip”

Leave a Reply

Your email address will not be published. Required fields are marked *