Email Your Raspberry Pi IP Address on Boot

pi-ip-1.png

A common complaint from Raspberry Pi owners is when running headless (no monitor or keyboard). If the Pi reboots then you lose your login session and often the previous IP address.

Using a something.local hostname sometimes works, but knowing the IP address is often more useful.

Here is a quick Python script to add to your rc.local file so it emails you on bootup.

Code


In this script I am using the Mailgun API so the message is less likely to end up in spam. You get a ton of free emails with Mailgun so it will not cost you a penny.

Add a text file containing your API key to your directory and call it mailgun-api.txt - that way you don't need to store the key in your script.

import subprocess
import requests

# load API key from file
inFile = open('/home/pi/mailgun-api.txt', 'r')
api_key = inFile.readline().rstrip()
inFile.close()

# get host and IP
this_host = subprocess.check_output("hostname", shell=True).rstrip()
IP_line = subprocess.check_output("hostname -I", shell=True).rstrip()


# send via Mailgun
def send_message():
    return requests.post(
        "https://api.mailgun.net/v3/YOURHOST.mailgun.org/messages",
        auth=("api", api_key),
        data={"from": "Bot <pibot@YOURHOST.mailgun.org>",
              "to": ["your@emails.com"],
              "subject": "MY IP: " + IP_line,
              "text": this_host + " = host and " + IP_line + " is my IP!"})

print send_message()
H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center