I do a lot of Raspberry Pi projects – often creating them in one place and using them in another. While it is easy enough to use SSH, VNC or HTML to access a device, if it’s being moved from one network to another, it can be challenging to know its ip address. Sure, you may be able to log into a local router and look it up, but I thought it would be easier if I just had the RPi email me with its current ip address.
Thankfully, Cody Giles created a tutorial on elinux.com outlining how to do this. His Python script runs on the RPi on startup, finds its ip address(es) and then emails this information to a predetermined address. I started with his code, but ended up changing it to meet my needs by also sending a message via Telegram.
In order to allow a Python script to send email through a Gmail account, you may need to enable an “App Password” for your sending account.
Step #1: Create the Python Script
Copy the following and paste it into a text editor. You must change the ‘to’ address, as well as the ‘gmail_user’ and ‘gmail_password’ for the sending account in the lines below the pound sign lines about 25 lines from the top. Save this file as a python script in the home directory named startup_email.py.
import subprocess
import smtplib
from email.mime.text import MIMEText
import datetime
import smtplib
import requests
from requests.structures import CaseInsensitiveDict
import sys
import time
time.sleep(10)
arg='ip route list' # Linux command to retrieve ip addresses.
# Runs 'arg' in a 'hidden terminal'.
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data1 = p.communicate() # Get data from 'p terminal'.
# Split IP text block into three, and divide the two containing IPs into words.
message = 'IP Addresses for Node0XX:\n' #Replace XX with node number
print(' ')
print('data1[0] = ')
print(data1[0])
print(' ')
ip_lines = data1[0].splitlines()
for l in ip_lines:
if ('link' in str(l)):
temp = str(l)
print(temp)
print(temp.index('dev'))
print(temp.index('proto'))
print('temp = ' + temp)
tempmsg01 = temp[int(temp.index('dev ')+4):int(temp.index('proto ')-1)]
tempmsg02 = temp[int(temp.index('src ')+4):int(temp.index('src ')+19)].replace(' ','').replace('m','').replace('e','').replace('t','')
print('tempmsg = ' + tempmsg01 + ': ' + tempmsg02)
message = message + '\n' + tempmsg01 + ': ' +tempmsg02
#print('message = ' + message)
################################ Second Telegram
token ='YOUR TELEGRAM TOKEN'
url2 = f'https://api.telegram.org/bot{token}/sendMessage'
data = {'chat_id': 'CHAT_ID_NUMBER,', 'text': message} # data1}
requestText = requests.post(url2, data).json()
print(requestText)
# Creates the text, subject, 'from', and 'to' of the message.
to = 'paulericksen@fava.email'
gmail_user = '<your gmail address>'
gmail_password = '<your gmail app password>'
smtpserver = smtplib.SMTP('smtp.gmail.com', 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.login(gmail_user, gmail_password)
today = datetime.date.today()
msg = MIMEText(message)
msg['Subject'] = 'IPs for nodeXX - %s' % today.strftime('%b %d %Y')
msg['From'] = gmail_user
msg['To'] = to
# Sends the message
smtpserver.sendmail(gmail_user, [to], msg.as_string())
# Closes the smtp server.
smtpserver.quit()
Step #2: Make the script executable.
Using Terminal, navigate to the home directory and make the script executable.
cd ~
sudo chmod +x startup_email.py
Setp #3: Run the Script on Startup.
We’ll add a line to the crontab to run the script whenever the device reboots.
crontab -e
Add the following lines to the crontab
@reboot /usr/bin/python3 /home/admin/Desktop/startup_email.py
Now, reboot the Pi and in about a minute, you should receive an email with your device’s IP address.