CaptainKorhonen
Posts: 1
Joined: Wed Jan 01, 2014 7:09 pm

Email external IP address

Wed Jan 01, 2014 8:13 pm

I'm sure this has been done (and posted) before, but here goes anyway:

I wrote this little shell script and thought I'd share it since it might come in handy to others as well. Simply put, it e-mails the external IP address to you if it has changed since the last time the script was run. I've only tried this with Gmail, but you're free to modify the script to suit your needs.

How to use:

First, you must update your package list and install mailutils and ssmtp:
sudo apt-get update
sudo apt-get install mailutils ssmtp
Then, open /etc/ssmtp/ssmtp.conf in a text editor (I used Nano)
sudo nano /etc/ssmtp/ssmtp.conf
Edit the mailhub line so that it looks like this:
mailhub=smtp.gmail.com:587
and add these to the end of the file (replace the AuthUser and AuthPass values with your gmail address and password):
AuthUser=[email protected]
AuthPass=yourgmailpassword
UseSTARTTLS=YES
Save the file. Then open /etc/ssmtp/revaliases in a text editor...
sudo nano /etc/ssmtp/revaliases
...and add this to the bottom of the file, again replacing "yourgmailaddress" with your own Gmail login:
root:[email protected]:smtp.gmail.com:587
All that is needed now is the script itself.

A quick explanation on how it works: When you run it for the first time, it retrieves your external IP address and stores it in a file called "ip.txt". This file will be created in the same folder as the script. Then, if the script is run again, it will load the previous IP address from the file, and will also check your current address. If these two match, i.e. the address has not changed, the script will just exit. If they do not match (the address has changed), the new IP address will be written to the text file (overwriting the old one) and emailed to you. Then the script will exit.

Put the subject of the message between the quotes in SUBJ, and the email address of the recipient between the quotes in EMAIL.

Code: Select all

#!/bin/sh

SUBJ=""
EMAIL=""

ip1=""
ip2=""

read ip1 < ip.txt
ip2=$(wget -qO- ifconfig.me/ip)

if [ "$ip1" = "$ip2" ]
then
  exit
else
  echo "$ip2" > ip.txt
  echo "$ip2" | mail -s $SUBJ $EMAIL
  exit
fi
Save the file. You can test it by running "sh *scriptnamehere*.sh". It will show an error on the first start as it is trying to load data from a file that doesn't exist. You can safely ignore this. You should receive an e-mail containing your external IP address. The script has also created the "ip.txt" file. If you open it, you can see that it contains your "old" IP address.

Now, the part where we make it run automatically. We're going to use Cron, which is a program you can use to schedule things. This should be installed by default.

First, open the Cron configuration file:
sudo crontab -e
Then add this line at the bottom:
0,15,30,45 * * * * sh *full path to script here*/*scriptnamehere*.sh &>/dev/null
I will not go into detail on what the different values do - there are plenty of tutorials and manuals online. The above line runs the script every 15 minutes, 24/7. It will only send the email message if the IP address has changed. As for the &>/dev/null part at the end - don't ask me what it is or how it works. All I know is that it stops Cron from sending useless error reports and other things to your email :lol:


That is all. This should be useful in case you regularly connect to your RasPi from outside your local network. Feel free to post here if you have any questions and I can at least try to help ;)

~CK

txt3rob
Posts: 365
Joined: Sat Aug 11, 2012 3:45 pm
Contact: Website

Re: Email external IP address

Thu Jan 02, 2014 12:49 pm

Sorry to slightly hijack this thread.

i have a script to sms you the ip via smspi.co.uk

https://github.com/txt3rob/SMS-PI/blob/ ... /smsip.php
The Raspberry Pi Hell Guy - Random Ramblings to assist me and others.
http://raspberrypihell.blogspot.com
My Github - http:/www.github.com/random-robbie/
http://www.smspi.co.uk - send free uk sms via your raspberry pi from here

AquaMan
Posts: 14
Joined: Wed Dec 19, 2012 12:01 am

Re: Email external IP address

Sat Jan 04, 2014 3:58 pm

Nicely written. I was trying something similar a few months ago and then found a really slick website called https://www.carriots.com/

So instead of sending me an email directly, it would send an update the carriots webpage. The idea behind carriots is that it listens for events (like the RPi sending a new IP) and executes a small script. That script could be to send you an email, or a txt, or to just sit there doing nothing.

What's neat is that you can then make a free webpage using http://www.000webhost.com/ and with bit of fiddling create a webpage that asks Carriots what your RPi ip address and displays it.

If you RPi is hosting a server, you can use the webhost page as your default start page, and then have it link you to your RPi page based on it's current ip address--you can even have check if the pi is on or off!

serpent
Posts: 3
Joined: Mon Mar 10, 2014 10:17 am

Re: Email external IP address

Sat Mar 29, 2014 3:06 pm

This script works good upto the actual email part.

if I type in this command, i recieve an email

Code: Select all

sudo echo testbody | mail -s testsubject [email protected]
however when i test the script i get the following error

Code: Select all

mail: cannot send message: Process exited with a non-zero status
the script was copied exactly and when run the ip.txt file updates with the latest ip, i also made sure the SUBJ= has no spaces

EDIT

Half Solved this one on my own, for some reason it didnt like me testing the sh file with sudo, if i just called it normally it works, however the writing to the ip.txt fails due to no sudo, and i manually changed the ip.txt file to a random ip, waited 15 minutes, it changed back to the actual ip, but didnt send the email.

txt3rob
Posts: 365
Joined: Sat Aug 11, 2012 3:45 pm
Contact: Website

Re: Email external IP address

Wed Apr 02, 2014 11:56 am

you could use sms also if you are in the uk

https://github.com/txt3rob/SMS-PI/blob/ ... /smsip.php
The Raspberry Pi Hell Guy - Random Ramblings to assist me and others.
http://raspberrypihell.blogspot.com
My Github - http:/www.github.com/random-robbie/
http://www.smspi.co.uk - send free uk sms via your raspberry pi from here

antwerx
Posts: 1
Joined: Thu Apr 03, 2014 8:16 pm

Re: Email external IP address

Thu Apr 03, 2014 8:27 pm

I had trouble with email failing to send until I set an Application-Specific Password within security settings https://www.google.com/settings/account in my Gmail account.

This was in the logs and how I diagnossed the issue. I followed the URL in the error message.

Code: Select all

Apr  3 20:11:28 raspberrypi sSMTP[3681]: Authorization failed (535 5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 d9sm26370616oex.6 - gsmtp)
Hope this helps.

Grimster
Posts: 1
Joined: Sun Apr 06, 2014 4:39 pm

Re: Email external IP address

Sun Apr 06, 2014 4:45 pm

Great script OP, thanks.

Just a slight change I had to make in the script was ensuring that absolute paths were specified for ip.txt in the script when running form chron, running manually was working fine and is probably something to do with the background user not being me. I can also confirm that this works with different smtp providers and port configurations.

I incidentally also found that icanhazip.com returned a quicker IP result (for me at least).

Thanks very much, most appreciated.

lepikova
Posts: 1
Joined: Thu Apr 24, 2014 5:48 am

Re: Email external IP address

Thu Apr 24, 2014 6:01 am

Hi,
I'm new to all this and little confused
I don't understand what to do after this step:

root:[email protected]:smtp.gmail.com:587
Shall I save and close "revaliases" file, or continue to type a code in that file?

Do I need to open a new file, and where it should be save?
It would be highly appriciated if somebody can guide me slowly through the process.
Thanks,
lepikova

MarkDG
Posts: 2
Joined: Sun Apr 27, 2014 1:15 pm

Re: Email external IP address

Sun Apr 27, 2014 1:35 pm

I am also very new to the RPi world. I am trying to set my system up for sending simple emails out. I do not need to receive email. I followed the instructions listed above for setting up mail. When I tested this from the command line I get the following:

[email protected] ~ $ mail -s "Test"
To: [email protected]
Cc:
This is a test

Cannot open mailer: No such file or directory
cannot send message: No such file or directory
[email protected] ~ $

Any suggestions?

Thanks.

pwl
Posts: 18
Joined: Wed Jul 25, 2012 1:18 pm
Location: Poland
Contact: Website

Thu Jul 17, 2014 9:44 pm

@MarkDG

Code: Select all

sudo echo testtext | mail -s testsubject [email protected]
Use this for cheking and see if there will be errors.



@CaptainKorhonen
I used script that you provided in this post but I had some problems with it. It have been sending emails each 15 min without any IP change.
I think that you'll find this script better working. It was written by a friend of mine (c) Esio and it's working perfectly. It only sends emails when there will be IP change.

Remember to instal perl if you don't have it yet.

Code: Select all

sudo apt-get install libwww-perl
sudo apt-get install libmime-lite-perl
touch ipadr.pl
nano ipadr.pl
paste the code copied from below. save and exit editor

Code: Select all

#!/usr/bin/perl

use LWP::UserAgent; # sudo apt-get install libwww-perl
use HTTP::Request;
use MIME::Lite; # sudo apt-get install libmime-lite-perl

my $URL = 'http://ifconfig.me/ip';
my $MAX_TRIES = 5;
my $SLEEP_BETWEEN_TRIES = 20;
my $FILE = '/home/pi/ipadr/ip.txt'; #change this if you use different location for the storing ip info
my $EMAIL = '[email protected]';

my $agent = LWP::UserAgent->new(env_proxy => 1,keep_alive => 1, timeout => 30);
my $header = HTTP::Request->new(GET => $URL);
my $request = HTTP::Request->new('GET', $URL, $header);
my $response;
my $tries = 1;

do
{
        $response = $agent->request($request);
        if($response->is_error)
        {
                print "URL: $URL tries: $tries\n";
                print "Got Error: " . $response->code . ': ' . $response->message. "\n";
                $tries++;
                if($tries <= $MAX_TRIES)
                {
                        sleep $SLEEP_BETWEEN_TRIES;
                }
        }
}
until(($response->is_success) || ($tries > $MAX_TRIES));

if($response->is_success)
{
    if($response->content =~ /((\d{1,3})(\.)){3}\d{1,3}/)
    {
        my $ip = $response->content;
        $ip =~ s/[^0-9.]*//g;

        print 'Your external IP address is: ' . $ip . "\n";

        if(open(my $F, "<$FILE"))
        {
            my $file_ip = <$F>;
            close $F;

            if($file_ip =~ /((\d{1,3})(\.)){3}\d{1,3}/)
            {
                $file_ip =~ s/[^0-9.]*//g;

                if($file_ip ne $ip)
                {
                    open F, ">$FILE" or die $!;
                    print F $ip;
                    close F;

                    print 'External IP change. New IP: ' . $ip . "\n";

                    $msg = MIME::Lite->new(
                                     From     => '[email protected]',
                                     To       => $EMAIL,
                                     Subject  => 'External IP change: ' . $ip,
                                     Data     => 'Your new external IP address is: ' . $ip . "\n"
                                     );

                    $msg->send or die $!;
                    print "Email Sent Successfully\n";
                }
            }
        }
        else
        {
            open F, ">$FILE" or die $!;
            print F $ip;
            close F;

            print 'Created external IP configuration file with data: ' . $ip . "\n";
        }
    }
    else
    {
        print 'Content contains invalid data: ' . $response->content . "\n";
    }
}
elsif($response->is_error)
{
        print "Sorry, was unable to get your external IP address\n";
}

Code: Select all

nano /etc/crontab
Paste this in new line to run the IP check every 15 minutes and remember to provide your location for the script

Code: Select all

*/15 * * * *    root    /home/pi/ipadr/ipadr.pl &>/dev/null

User avatar
DougieLawson
Posts: 34561
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK
Contact: Website Twitter

Re: Email external IP address

Thu Jul 17, 2014 11:37 pm

Here's my version (in python)

Code: Select all

#!/usr/bin/python3
import time
from datetime import datetime
import smtplib
from email.mime.image import MIMEImage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import socket
import os
from urllib.request import urlopen
import json

f_time = datetime.now().strftime('%a %d %b @ %H:%M')

gw = os.popen("ip -4 route show default").read().split()
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((gw[2], 0))
ipaddr = s.getsockname()[0]
gateway = gw[2]
host = socket.gethostname()
ip = urlopen('http://httpbin.org/ip').read()
ip = ip.decode('utf-8')
ip = json.loads(ip)

localIP = "IP:" + ipaddr + " GW:" + gateway + " Host:" + host
publicDomain, alias, addresslist = socket.gethostbyaddr(ip['origin'])

toaddr = '[email protected]'    # redacted
me = '[email protected]' + publicDomain
subject = 'IP Address @ ' + f_time

msg = MIMEMultipart()
msg['Subject'] = subject
msg['From'] = me
msg['To'] = toaddr
msg.preamble = "IP Address @ " + f_time

ipDetails = "Local " + localIP + "\nPublic IP: " + ip['origin'] + "\nPublic Domain: " + publicDomain

ipstuff = MIMEText(ipDetails, 'plain')
msg.attach(ipstuff)

try:
   s = smtplib.SMTP('localhost')
   s.send_message(msg)
   s.quit()
except:
   print ("Error: unable to send email")
Note: Having anything remotely humorous in your signature is completely banned on this forum.

Any DMs sent on Twitter will be answered next month.

This is a hippy & doctor free zone.

drew2000
Posts: 1
Joined: Sat Aug 30, 2014 3:52 pm

Re: Email external IP address

Sat Aug 30, 2014 3:56 pm

Hi All,
I have this configuration working, with one exception.

Instead of receiving one email to the address specified, I also get bounce backs from other local addresses:

[email protected] (this is the user running the cron job and the hostname of the device)
[email protected]
[email protected]

I can't figure out where these other aliases are listed on the system and why the script is sending it to all of these accounts instead of just the real address.

Could it be that they are defined under the user account "pi" somewhere?

Thanks,
Andrew

mikael_trieb
Posts: 1
Joined: Fri Oct 10, 2014 8:51 pm

Re: Email external IP address

Sat Oct 11, 2014 6:12 am

If you are using MQTT you can use this method. Calling this python script will publish a message to a mqtt broken with the external ip address of the computer. Anyone connected to that broker can then subscribe to that message and thereby get to know the ip address.

Code: Select all

#!/usr/bin/python3
import urllib.request
import json
import paho.mqtt.client as mqtt

DEBUG = False

def getIP():
	request  = urllib.request.Request('http://httpbin.org/ip')
	response = urllib.request.urlopen(request)
	#obj = json.load(response)
	str_response = response.readall().decode('utf-8')
	obj = json.loads(str_response)
	return obj['origin']

def on_connect(client, userdata, rc):
	if(DEBUG):
		print("Connected to broker")
	client.subscribe("your_topic/#")

def on_message(client, userdata, msg):
	if(DEBUG):
		print("Received message")
	print(msg.topic, ": ", str(msg.payload))

# Initiate mqtt-client
mqttc = mqtt.Client()
mqttc.on_connect = on_connect
mqttc.on_message = on_message

mqttc.connect(<broker address>, 1883, 60)
mqttc.loop_start()

running = True

while running:
	# Get the external IP
	IP = getIP()
	if(DEBUG):
		print(IP)
	mqttc.publish("your_topic/externalIP", IP)
	time.sleep(5)
	mqttc.loop_stop()
	running = False
I use the mosquitto broker: http://mosquitto.org/
and the paho mqtt lib for python https://pypi.python.org/pypi/paho-mqtt

flyboy12
Posts: 2
Joined: Wed Nov 12, 2014 1:39 pm
Location: Louisville KY
Contact: Website

Re: Email external IP address

Thu Nov 13, 2014 6:34 pm

All that is needed now is the script itself.

A quick explanation on how it works: When you run it for the first time, it retrieves your external IP address and stores it in a file called "ip.txt". This file will be created in the same folder as the script. Then, if the script is run again, it will load the previous IP address from the file, and will also check your current address. If these two match, i.e. the address has not changed, the script will just exit. If they do not match (the address has changed), the new IP address will be written to the text file (overwriting the old one) and emailed to you. Then the script will exit.

Put the subject of the message between the quotes in SUBJ, and the email address of the recipient between the quotes in EMAIL.

Code: Select all

#!/bin/sh

SUBJ=""
EMAIL=""

ip1=""
ip2=""

read ip1 < ip.txt
ip2=$(wget -qO- ifconfig.me/ip)

if [ "$ip1" = "$ip2" ]
then
  exit
else
  echo "$ip2" > ip.txt
  echo "$ip2" | mail -s $SUBJ $EMAIL
  exit
fi
Save the file. You can test it by running "sh *scriptnamehere*.sh". It will show an error on the first start as it is trying to load data from a file that doesn't exist. You can safely ignore this. You should receive an e-mail containing your external IP address. The script has also created the "ip.txt" file. If you open it, you can see that it contains your "old" IP address.

Now, the part where we make it run automatically. We're going to use Cron, which is a program you can use to schedule things. This should be installed by default.

First, open the Cron configuration file:
sudo crontab -e
Then add this line at the bottom:
0,15,30,45 * * * * sh *full path to script here*/*scriptnamehere*.sh &>/dev/null

~CK
[/quote]

Where does this script need to be saved? How does the Pi know where to look for the script when the Pi reboots and should run it?

thanks!

mgbjackson
Posts: 1
Joined: Fri Dec 05, 2014 10:07 pm

Re: Email external IP address

Fri Dec 05, 2014 10:13 pm

drew2000 wrote:Hi All,
I have this configuration working, with one exception.

Instead of receiving one email to the address specified, I also get bounce backs from other local addresses:

[email protected] (this is the user running the cron job and the hostname of the device)
[email protected]
[email protected]

I can't figure out where these other aliases are listed on the system and why the script is sending it to all of these accounts instead of just the real address.

Could it be that they are defined under the user account "pi" somewhere?

Thanks,
Andrew
Heya,

I had the same problem. If you enclose $SUBJ in "" on the line with "echo "$ip2" | mail -s $SUBJ $EMAIL" it should fix it. (i.e. the new line would be echo "$ip2" | mail -s "$SUBJ" $EMAIL

Hope this helps!

raf610
Posts: 2
Joined: Sat Dec 06, 2014 9:11 pm

Re: Email external IP address

Sat Dec 06, 2014 9:22 pm

hi
thanks for post but a have a problem
script is ok, when I start it by shell send mail correctly.
But when i put instruction in crontab then my rasp sen me e-mail any 15 minutes with last ip address.
Why, can you help me?
ciao

minca
Posts: 3
Joined: Thu Oct 23, 2014 9:27 am

Re: Email external IP address

Fri Feb 27, 2015 2:21 pm

Hi,

thx for that Script.

I've updated it a bit my way and it will run only on reboot (power outage):

file location:

Code: Select all

cd /home/userid/
create file:

Code: Select all

touch ip.txt
create script file:

Code: Select all

vim ipcheck.sh
paste in content:

Code: Select all

#! /bin/sh

SUBJ="Warning: Raspberry Pi - new IP Address"
SUBJ2="Warning: Raspberry Pi was restarted"
EMAIL="[email protected]"

ip1=""
ip2=""

read ip1 < ip.txt
ip2=$(wget -qO- ifconfig.me/ip)

if [ "$ip1" = "$ip2" ]
then
  echo "Your Raspberry was restarted, the IP Address is the same as before."| mail -s "$SUBJ2" $EMAIL;
else
  echo "$ip2" > ip.txt;
  echo "New IP Address was assigned to your router: $ip2" | mail -s "$SUBJ" $EMAIL;
  exit;
fi

make it "executable"

Code: Select all

chmod +x ipcheck.sh
you can test it:

Code: Select all

./ipcheck.sh
then add it to "cronjob list" on start-up:

Code: Select all

crontab -e
go to bottom and paste:

Code: Select all

@reboot /home/userid/ipcheck.sh
press ctr+o to save, hit enter (don't change filename) and then ctrl+x to exit

cheers

andreagosto
Posts: 1
Joined: Thu Mar 19, 2015 7:46 pm

Re: Email external IP address

Thu Mar 19, 2015 7:50 pm

i can't set user mail alias, just for root work..

Piroman
Posts: 6
Joined: Sat Feb 07, 2015 11:04 pm

Re: Email external IP address

Sun Mar 22, 2015 11:12 am

I have one with PHP ! :)

make your Raspbery PI call home

its small script for checking external ip and sending to you by mail
(checking for your external IP and sending mail , see in junk mail)

Code: Select all

sudo nano checkip

Code: Select all

?php
$externalContent = file_get_contents('http://icanhazip.com/plain');
preg_match('/\b(?:\d{1,3}\.){3}\d{1,3}\b/', $externalContent, $m);
$externalIp = $m[0]

mail('your e-mailhere', 'External IP', $externalIp);

make it run every day 06:00 with cron :

Code: Select all

crontab -e
(add line to bottom)

Code: Select all

00 06 * * * /usr/bin/php /home/pi/checkip

sendmail should be installed by defaulf if not then :

Code: Select all

sudo apt-get install sendmail






And i made second with "sed" when i worked on IpSec for Blackberry VPN .

here is http://wario-linux.blogspot.dk/2013/09/ ... iew=mosaic
Scroll down "Guide for people with dynamic IP:"

eejoes
Posts: 1
Joined: Sat May 09, 2015 4:04 pm

Re: Email external IP address

Sat May 09, 2015 4:08 pm

please edit your gmail security protection --> set to less secure, and try. hope fixed it

sIRwa2
Posts: 1
Joined: Sat Mar 26, 2016 10:27 pm

Re: Email external IP address

Sat Mar 26, 2016 10:32 pm

I too had to go to gmail and allow the use of unsecure apps to be able to send mail.

but every time i manually test the script. the correct mail is send to the correct mail recipient, but ALSO to [email protected] and to [email protected]

so i get 2 Delivery Status Notification (Failure) mails on my send mailbox and 1 on my receive mailbox.

anyone knows where sSMTP gets the other 2 addresses from?

georgestewart88
Posts: 83
Joined: Fri Apr 15, 2016 6:19 am

Re: Email external IP address

Mon Apr 25, 2016 8:53 am

sIRwa2 wrote:I too had to go to gmail and allow the use of unsecure apps to be able to send mail.

but every time i manually test the script. the correct mail is send to the correct mail recipient, but ALSO to [email protected] and to [email protected]

so i get 2 Delivery Status Notification (Failure) mails on my send mailbox and 1 on my receive mailbox.

anyone knows where sSMTP gets the other 2 addresses from?
Make sure your subject does not have spaces.

Aephir
Posts: 5
Joined: Sat Mar 11, 2017 1:16 am

Re: Email external IP address

Sat Mar 11, 2017 2:09 am

Thanks, this was just what I needed.

Is it possible to send the email from a "burner" gmail, but send to my "usual" gmail? I guess in case anyone gets access to my pi, the password to the gmail sending the email is stored in plain text. Not likely to be an issue, but if it is possible, it would make me sleep better at night.

Cheers!

shudhanshh
Posts: 1
Joined: Wed Mar 29, 2017 10:39 am

Re: Email external IP address

Wed Mar 29, 2017 10:44 am

sir, there is an error occurring when i am executing that script, it could not find the ip.txt file, i tried to find that file but i think it is not present on my pi. please guide me to solve this issue as soon as possible

agent_adam
Posts: 1
Joined: Sun Jun 25, 2017 5:09 pm

Re: Email external IP address

Sun Jun 25, 2017 11:25 pm

Such a simple solution to something I have been looking to do for a while. Worked without issues.
I use ddclient which is great for changing the external IPs but I only have some services attached to my domain. Others I need to know my IP address.

Thanks a lot for posting.

Return to “Networking and servers”