Have Raspberry Pi Email Your IP

Hi all.

I was scrolling through reddit when I noticed a post in the /r/raspberry_pi section.

In the post, the user is showing how he plugs in his Pi to the school network but then has to IP scan the network to find his Pi since he’s running it headless.

I guess that works, especially with using native shell commands to form a ping sweep.

But that might be against the network’s terms, he might have trouble finding it if he doesn’t know the subnet, who knows.

So I whipped up a script to kick off a cron job after boot to run a script which will give us the Pi’s IP if your’e running headless.

First off, we need some packages installed and configured. My example uses Gmail as the SMTP server.

You’d do the following:

sudo apt-get install mailutils
sudo apt-get install ssmtp
sudo vi /etc/ssmtp/ssmtp.conf

Add the following:

AuthUser=Your-Gmail-Account@gmail.com
AuthPass=Your-Gmail-Password
FromLineOverride=YES
mailhub=smtp.gmail.com:587
UseSTARTTLS=YES

Now to make the script:

#! /bin/bash
 
#Wait to ensure system is up with an IP
sleep 60
 
#Set variable to get interface's IP assuming interface is eth0
 
IP=$(/sbin/ifconfig eth0 | grep -E '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}')
 
#Send mail to admin with IP address in body
 
#Set subject
SUBJECT="Pi's Current IP"
 
# Email To ?
EMAIL="admin@somesite.com"
 
# Email text/message
EMAILMESSAGE="/tmp/IP.txt"
echo "Your IP is:"> $EMAILMESSAGE
echo ${IP} >>$EMAILMESSAGE
 
# send an email using /bin/mail
/usr/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE

So what we’re doing here is waiting to ensure the system is up, parsing ifconfig’s output with grep for the relevant string we’d like, and then forming a quick email message to deliver via the previously installed packages.

Now all that’s left to do is to configure it as a cron job.

crontab -e

And add

@reboot /path/to/script

And that should be it. Anytime your Pi boots or reboots, it’ll kick out an email after a minute with it’s IP.

Cheers,

Marcus

Leave a Reply