Headless RaspPi: Tell Me Where You Are

I like several of the little SBC (Single Board Computer) systems that are available, despite having a love/hate relationship with my favourite – the ODROID C2. For the minute I’m stuck with just a Raspberry Pi 3 as a little SBC, so needs must when the devil, etc etc…

Anyway, when you control your own network, as I used to, it doesn’t really matter what IP DHCP decides to assign to each system. I could look it up on the router easily enough, or even fix an IP address based on MAC address.

OK, fine… but what if you don’t control your router?

Well, you could brute-force scan the entire known IP range of the network using NMAP… (nmap -sS xxx.yyy.zzz.0/24) but that seems a little extreme. It works in a pinch, though, and might be the only way of finding it that all important first time.

Once you know where it is, however, how can you keep it? On a network you don’t control, you can get jumped around the IP range depending on how the router is feeling and how many others are connected. Not very useful.

Here’s a little script modified from another one that didn’t work for me… (requires Python 2, not Python 3…)

Ah, and I found where the mods come from…!

This will send you an e-mail telling you your headless systems’ IP when the RPi boots.

Just add this to a file with vi bootupEmail.py, then chmod +x it:

import subprocess
import smtplib
import socket
from email.mime.text import MIMEText
import datetime
# Change to your own account information
to = 'me@example.com'
gmail_user = 'test@gmail.com'
gmail_password = 'yourpassword'
smtpserver = smtplib.SMTP('smtp.gmail.com', 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo
smtpserver.login(gmail_user, gmail_password)
today = datetime.date.today()
# Very Linux Specific
arg='ip route list'
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate()
split_data = data[0].split()
ipaddr = split_data[split_data.index('src')+1]
my_ip = 'Your ip is %s' %  ipaddr
msg = MIMEText(my_ip)
msg['Subject'] = 'IP For RaspberryPi on %s' % today.strftime('%b %d %Y')
msg['From'] = gmail_user
msg['To'] = to
smtpserver.sendmail(gmail_user, [to], msg.as_string())
smtpserver.quit()

You’ll also need to add python /home/user/bin/scripts/bootupEmail.py to your rc.local, just before the exit 0 at the end.

IMPORTANT: Obviously, since you just put your Gmail password in a plain text file (really, really bad security practice!) just set up a gmail account to only do this one thing. Or, if you want, you could set up a mailserver on your Pi.

That may become the topic of a future post. In fact, it probably will, because I can’t believe I just suggested putting a password in plaintext.

Leave a Reply

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