I recently moved house and with that had to adjust to a new internet service that is unfortunately not as reliable as my old one. As I rely on my raspberry pi as a remote media server, I need to know what the IP address is, which is a bit of a pain when it keeps changing while you’re out the house.
I started thinking “Maybe there’s a way I could automate the emailing of my IP address once a day” so I started investigating CLI mailers.
Initially I looked at sendmail but it seemed a little bit overkill for what I needed, and I got a little bit lost in the configuration options, but perhaps that’s just my poor attention span.
The next step was setting the pi to obtain the external ip address, and for this I used curl with checkip.dyndns.org and sent the output to a text file called todaysip.txt. This can be put in a script with the ssmtp email command, and it looks like this:
date > date.txt && curl -s checkip.dyndns.org | sed -e 's/.*Current IP Address: //' -e 's/<.*$//' > todaysip.txt && paste date.txt todaysip.txt >> today.txt && tac today.txt | mail -s "IP Address" email@example.com
The next step was setting crontab to run the script at midday everyday. Job’s a good ‘un.**
If there’s a more elegant way of achieving the same result, I’d be interested in hearing it as this is a bit of a quick ‘n’ dirty solution.
*You will need to set-up a separate app password if you use Gmail’s 2-factor authentication.
**It took me a bit of troubleshooting to get this to work, but ultimately I used /bin/sh rather than /bin/bash – See source below
EDIT: Added date stamp to script. Probably in an overkill kinda way.