Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamically update hosts file from file

I have a Raspberry Pi at my dads house that is used as a "Hive" (Heating/Water control).
My dad has a dynamic IP provided by his ISP, when it changes the Pi updates a text file on my server (via ssh). This is then used by me to SSH in and by him to get to the web UI via a URL on my domain "/cleres".

Currently I have an ugly bash script that copies my entire hosts file except the last line (his ip) to a temp file, gets the new IP from the text file, and updates the hosts file appending

XXX.XXX.XXX.XXX      dad

I feel this is not the best way to do this, however every post (I found) about dynamic hosts file updating seems to be people updating it with their own local DHCP address. I don't want to use dyndns or noip because it is unnecessary. I already have the IP, i just need a way of aliasing it on my server.

TLDR I am wondering if there is a better way to update my hosts file than copying the whole thing and appending a new IP & host.
My domain is here if anyone is interested.

---UGLY BASH SCRIPT---

ip="$(cat /media/dad/dadextip.txt)"
check="$(cat /etc/hosts | grep $ip | sed -e 's/\< Dad\>//g')"
if [[ $check != *[^0-9]* ]]; then
        cat /etc/hosts | grep -v Dad > /tmp/tmphosts
        cat /tmp/tmphosts > /etc/hosts
        echo "$ip          Dad" >> /etc/hosts
        cat /tmp/tmphosts > /var/spool/postfix/etc/hosts
        echo "$ip          Dad" >> /var/spool/postfix/etc/hosts
        cat /etc/webmin/servers/1448542326.serv | grep -v host > /tmp/tmphosts
        cat /tmp/tmphosts > /etc/webmin/servers/1448542325.serv
        echo "host=$ip" >> /etc/webmin/servers/1448542326.serv
        exit 0
elif [ $check != $ip ]; then
        cat /etc/hosts | grep -v Dad > /tmp/tmphosts
        cat /tmp/tmphosts > /etc/hosts
        echo "$ip          Dad" >> /etc/hosts
        cat /tmp/tmphosts > /var/spool/postfix/etc/hosts
        echo "$ip          Dad" >> /var/spool/postfix/etc/hosts
        cat /etc/webmin/servers/1448542326.serv | grep -v host > /tmp/tmphosts
        cat /tmp/tmphosts > /etc/webmin/servers/1448542326.serv
        exit 0
else
        exit 0
fi
like image 382
DBMage Avatar asked Oct 17 '25 02:10

DBMage


1 Answers

GNU sed can do in-file replacement (sed -i "s/<regex>/replacement/" /etc/hosts). Obviously you'd want to test the regex-replacement part without the -i option first until it works...

like image 129
DevSolar Avatar answered Oct 18 '25 14:10

DevSolar