Page 1 of 3

RPi IP Emailer

Posted: Mon Jun 25, 2012 8:52 am
by FeersumEndjinn
Ever taken your RPi to show a friend, but had to run it headless for whatever reason?

I recently took mine to show my brother, but with his 42" TV on the wall and his router in another room, I had to choose - networking or TV output?

I opted for networking and then realised my fatal flaw - I had no idea what IP address the RaspberryPi was given, so couldn't remote into it.

So, last night I wrote myself a little Python script that runs on boot. If it detects an IP address other than it's usual reserved address from my network, it emails me it's IP address with a timestamp (to ensure it is accurate/up to date).

It can be found here https://gist.github.com/2987424 which will be kept up to date with any minor revisions, or below:

Code: Select all

#!/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'

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:
	inet_line = ip_file.next()
	_time = time.asctime()
	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' % inet_string
	    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)
Once you download it and save it as whatever (I called it check_ip.py), run

Code: Select all

$ chmod 755 check_ip.py
$ sudo cp check_ip.py /etc/initid/
$ sudo update-rc.d check_ip.py defaults 19
This will run the script pretty much after everything else (with a priority of 19).

There are a few things to remember -

[*] Remember to change the FIXED_IP constant to be your usual Raspberry Pi IP address.
[*] Remember to change the emails addresses, stmp server, SSL port and user details.

It's up to you, but I registered a new gmail account to use for things like this so that I don't compromise my main email address.

Hopefully others besides myself will find it useful :)

Regards,
FeersumEndjinn/Morrolan

Re: RPi IP Emailer

Posted: Mon Jun 25, 2012 8:54 am
by FeersumEndjinn
Sorry, that should be:

Code: Select all

$ chmod 755 check_ip.py
    $ sudo cp check_ip.py /etc/init.d/
    $ sudo update-rc.d check_ip.py defaults 19
Regards,
FeersumEndjinn/Morrolan

Re: RPi IP Emailer

Posted: Mon Jun 25, 2012 12:04 pm
by MattHawkinsUK
Excellent idea, I like it.

If anyone wants to add the MAC address you can read it from "/sys/class/net/eth0/address"

Re: RPi IP Emailer

Posted: Tue Jun 26, 2012 4:22 pm
by ScorpAL
no-ip.com can help.

Your Raspberry will be on something like: myraspberry.noip.com
No matter with you current ip now. You will need just host name.

Re: RPi IP Emailer

Posted: Thu Jun 28, 2012 8:17 am
by FeersumEndjinn
no-ip.com wouldn't work in this instance - the dynamic DNS provided by no-ip.com and dyndns.com points only to the gateway for the network, i.e. the router's external ISP-allocated DHCP IP address. It doesn't point to the internal network IP address of the RaspberryPi.

When you don't have access to the router this ceases to be an option, as you can't do any port-forwarding and it is much more long-winded having to change router settings or watch the DHCP list on the router to watch the address as it is allocated etc.

Why would I do that when all I now have to do is pull out my phone and check my gmail? :mrgreen:

Re: RPi IP Emailer

Posted: Thu Jun 28, 2012 8:35 am
by SN
This is a nice idea, I like it.

Re: RPi IP Emailer

Posted: Thu Jun 28, 2012 8:40 am
by FeersumEndjinn
Sorry, on another note, the Gist is constantly being tweaked and updated - https://gist.github.com/2987424.

I've added the mac address (thanks to MattHawkinsUK) but at the moment it doesn't use it for anything, it just gives you the information in the body of the email.

If anyone has any comments or suggestions on how I can improve this (I will be changing it to use the tempfile module to avoid potential permissions issues) then please let me know :mrgreen:

Re: RPi IP Emailer

Posted: Fri Jun 29, 2012 11:17 am
by n3tw0rk5
Very handy, I was thinking of using a 3g dongle with an autodial script and then an ip email script so I could log in.
At least half of the work is done now cheers :D

Re: RPi IP Emailer

Posted: Fri Jun 29, 2012 11:24 am
by clickykbd
Nice. Have had the thought to do this, but was too lazy or distracted by other things. It's definitely worthy to display on little baby LCDs or digitized LED displays for those playing with such hardware too.

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 9:52 am
by EvdM
Hi - I really like this idea and tried to implement it as a first 'project' on my RPi.
Unfortunately I cannot get it to work. I think that I followed the instructions to the letter, but running the script results in the following error:

Traceback (most recent call last):
File "/etc/init.d/check_ip.py", line 20, in <module>
ip_file = file('~/current_ip.txt', 'r')
IOError: [Errno 2] No such file or directory: '~/current_ip.txt'

And the file "current_ip.txt" is indeed generated in /home/pi

Unfortunately I do not (yet) know enough to find the issue in python myself. So any pointer or suggestion is much welcomed. Thanks!

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 11:38 am
by FeersumEndjinn
Ah ha, I know what causes this - as the script isn't running as *you*, i.e. pi, it doesn't understand the ~/ home prefix shortcut.

Instead, change it to show '/home/pi/current_ip.txt' on both lines and it will work fine.

Or if you want to keep your home folder tidier, replace it with: '/home/pi/scripts/current_ip.txt' .

Hopefully this will fix your issue.

I am working on using a different python module to create this file purely in RAM in a tempfile but it hasn't been fully tested yet - watch this space.

Regards,

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 12:16 pm
by EvdM
Thanks a lot for your really quick response!
Your suggestion did do the trick. It now mails my IP and MAC. Only thing is that it does so on shutdown, rather than boot. That kind of defeats its purpose ;-)
Best regards,
EvdM

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 1:17 pm
by FeersumEndjinn
:o

That is rather strange! The init.d folder is the initialization/boot script folder, so I've never known it do that before!

cd into the /etc/init.d folder, and run:

Code: Select all

$  sudo update-rc.d check_ip.py defaults 19
The dollar sign obviously being the prompt (don't type that bit :D )

Also, type:

Code: Select all

$  sudo nano /etc/init.d/check_ip.py
And change the 'print' line to say something a little more obvious - you can comment out the current line with a # at the beginning if you don't want to permanently change the script - try doing that, and immediately below (and indented the same) type:

Code: Select all

print '++++++++++++++++ MELON MELON MELON ++++++++++++++++'
Then before you type startx, look for this line above the login prompt - if you see it, it is emailing at the correct point.

5 points to anyone who can tell me where the above line comes from ;)

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 1:34 pm
by grumpyoldgit
Is it from Spaced, when they all go to see Vulva's installation? I'm sure it's what Daisy says over the closing credits.

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 2:01 pm
by piglet
FeersumEndjinn wrote:I am working on using a different python module to create this file purely in RAM in a tempfile but it hasn't been fully tested yet - watch this space.
I don't do Python, but can't you just grab the command output into a string?:

Code: Select all

import os
x = os.popen('ip -4 addr | grep eth0').read()

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 2:24 pm
by FeersumEndjinn
piglet wrote:
FeersumEndjinn wrote:I am working on using a different python module to create this file purely in RAM in a tempfile but it hasn't been fully tested yet - watch this space.
I don't do Python, but can't you just grab the command output into a string?:

Code: Select all

import os
x = os.popen('ip -4 addr | grep eth0').read()

Correct you can, but that ip -4 addr returns a lot more than just the plain IP - take a look at this image:

Image

Apologies for the screenshot, I had to remote home to run the command so it was easier to take a screenshot than type it all out.

As you can see in the screenshot, it isn't as straightforward to grab only a small portion of that text, especially as I don't know regex or awk/sed type commands.

In Python there is a tempfile module which I will be upgrading this to shortly which will hold a small file (say 200 bytes) in memory for milliseconds, so whilst it's not the most efficient way of doing it, it was the most efficient within my knowledge/expertise without spending a lot longer learning new commands.

I found it easier to dump everything to text, then use string slicing to find what I was looking for.

That reminds me actually - I need to add something that WON'T try to email if no IP is detected! :D

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 2:33 pm
by grumpyoldgit
grumpyoldgit wrote:Is it from Spaced, when they all go to see Vulva's installation? I'm sure it's what Daisy says over the closing credits.
Thinking about it, she says Rabbits, Rabbits, Rabbits.

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 2:42 pm
by FeersumEndjinn
grumpyoldgit wrote:
grumpyoldgit wrote:Is it from Spaced, when they all go to see Vulva's installation? I'm sure it's what Daisy says over the closing credits.
Thinking about it, she says Rabbits, Rabbits, Rabbits.

Sorry, incorrect. It is from a book...

Or shall I say, a very large series of books. If any of you who know me in real life or know my surname, that's the biggest clue! :mrgreen:

Re: RPi IP Emailer

Posted: Thu Jul 05, 2012 10:13 pm
by FeersumEndjinn
I've been working on this a little more this evening - I've neatened up where you define your from, to etc. addresses by adding them as constants up at the top, so if you don't use gmail it's still easy to configure.

Remember, the TO and FROM can be the same email address!

The new gist is available at: https://gist.github.com/2987424

Or it can be grabbed below (without syntax highlighting)

Code: Select all

#!/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.  

################################################
###### Remember to set all constants here ######
################################################
FIXED_IP = '10.0.1.2'
IP_FILEPATH = '/home/pi/current_ip.txt'
SMTP_USERNAME = '[email protected]'
SMTP_PASSWORD = 'password'
SMTP_RECIPIENT = '[email protected]'
SMTP_SERVER = 'smtp.gmail.com'
SSL_PORT = 465
################################################

class bcolors:
    HEADER = '\033[95m'
    INFOBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'

    def disable(self):
        self.HEADER = ''
        self.INFOBLUE = ''
        self.OKGREEN = ''
        self.WARNING = ''
        self.FAIL = ''
        self.ENDC = ''

    
ipaddr_string = 'ip -4 addr > ' + IP_FILEPATH
subprocess.call(ipaddr_string, shell=True)
inet_string = ''

ip_file = file(IP_FILEPATH, 'r')
for line in ip_file:
        
    if 'eth0:' in line:
        inet_line = ip_file.next()
        _time = time.asctime()
        inet_string = inet_line[9:(inet_line.index('/'))]

    if inet_string != FIXED_IP:

			SUBJECT = 'IP Address from Raspberry Pi at: %s' % time.asctime()
			TO = SMTP_RECIPIENT
			FROM = SMTP_USERNAME
			text = 'The IP address is: %s' % inet_string
			BODY = string.join((
							'From: %s' % FROM,
							'To: %s' % TO,
							'Subject: %s' % SUBJECT,
							'',
							text
							), '\r\n')
			server = smtplib.SMTP_SSL(SMTP_SERVER, SSL_PORT)
			server.login(SMTP_USERNAME, SMTP_PASSWORD)
			server.sendmail(FROM, [TO], BODY)
			server.quit()

			print '[' + bcolors.INFOBLUE + 'info'  + bcolors.ENDC + ']' + ' Emailing eth0 IP address ' + inet_string + ' to ' + TO + ' from ' + FROM

ip_file.close()
I've added some colour to the line that prints out, so now it blends in with the rest of the boot sequence :)

And no, that email address isn't actually mine, so don't try it :)

Remember to check the first post for instructions.

Regards,

Re: RPi IP Emailer

Posted: Sat Jul 07, 2012 1:11 pm
by Ogoshi
I have an android application called 'Fing' which scans the LAN for devices and shows their ip and Mac addresses. If you're able to connect your phone to their net too then this could also be helpful.

Re: RPi IP Emailer

Posted: Sat Jul 07, 2012 2:01 pm
by FeersumEndjinn
Ogoshi wrote:I have an android application called 'Fing' which scans the LAN for devices and shows their ip and Mac addresses. If you're able to connect your phone to their net too then this could also be helpful.
Fing is also available for iOS, but some networks find this really intrusive and shut you down :)

Re: RPi IP Emailer

Posted: Sun Jul 29, 2012 1:27 am
by marc1
Great utility. One question...

Code: Select all

[email protected] ~/Desktop $ sudo update-rc.d check_ip.py defaults 19
update-rc.d: using dependency based boot sequencing
insserv: warning: script 'K01vncboot' missing LSB tags and overrides
insserv: warning: script 'check_ip.py' missing LSB tags and overrides
insserv: warning: script 'vncboot' missing LSB tags and overrides
I made my VNC server run at boot. But I am unclear what the above warning means. Any help interpreting?

Re: RPi IP Emailer

Posted: Sun Jul 29, 2012 1:37 am
by Paul Webster
IP_FILEPATH is created / written to by the script - you do not create this file yourself.
It is used to hold the current IP address.

Leads to a suggestion though ... if the current IP address is the same as the last one reported then no need to report it again.

Re: RPi IP Emailer

Posted: Sun Jul 29, 2012 1:41 am
by marc1
Thanks Paul, you are quick to reply. I ended up figuring that out and updated my post with another question.

Re: RPi IP Emailer

Posted: Sun Jul 29, 2012 7:22 pm
by mistaSteve
Nice utility to have, a couple things tho:
  • Latest version of the code needs to import the necessary modules at the beginning.
    For whatever reason, this mails me TWICE. Odd. It's like it runs at the start of the boot, then again at the end. So for example, I get the first email, try to log-in (ssh), am refused, but after the second, ssh works.
    Also at first I was getting several emails with blank IP addresses. So I added a check so it doesn't mail me blanks :)