-
-
Save t0mab/3017480 to your computer and use it in GitHub Desktop.
RaspberryPi IP address emailer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# The idea behind this script is if plugging a RaspberryPi into a foreign network whilst running it headless | |
# (i.e. without a monitor/TV), you need to know what the IP address is to SSH into it. | |
# | |
# This script emails you the IP address if it detects an ethernet address other than it's usual address | |
# that it normally has, i.e. on your home network. | |
import subprocess | |
import smtplib | |
import string | |
import time | |
FIXED_IP = '10.10.2.10' | |
# Will change this to use tempfile module to avoid permissions issues once I am back on a Pi/linux machine | |
ipaddr_string = 'ip -4 addr > ~/current_ip.txt' | |
subprocess.call(ipaddr_string, shell=True) | |
ip_file = file('~/current_ip.txt', 'r') | |
for line in ip_file: | |
if 'eth0:' in line: | |
_time = time.asctime() | |
_mac = file('/sys/class/net/eth0/address').read() # Don't know what you'll use it for atm, but I've included it | |
inet_line = ip_file.next() | |
inet_string = inet_line[9:(inet_line.index('/'))] | |
if inet_string != FIXED_IP: | |
print 'Found eth0: %s' % inet_string | |
SUBJECT = 'IP Address from Raspberry Pi at: %s' % time.asctime() | |
TO = '[email protected]' | |
FROM = '[email protected]' | |
text = 'The IP address is: %s and the mac address is %s' % (inet_string, _mac) | |
BODY = string.join(( | |
'From: %s' % FROM, | |
'To: %s' % TO, | |
'Subject: %s' % SUBJECT, | |
'', | |
text | |
), '\r\n') | |
server = smtplib.SMTP_SSL('smtp.gmail.com', 465) # NOTE: This is the GMAIL SSL port. | |
server.login('[email protected]', 'password') | |
server.sendmail(FROM, [TO], BODY) | |
server.quit() | |
ip_file.close() | |
# enable the following 2 lines to delete the text file afterwards, i.e. to make it a bit cleaner. | |
#_string = 'rm -f ~/current_ip.txt' | |
#subprocess.call(_string, shell=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment