User Tools

Site Tools


ip_email

A Python script to have your IP address emailed to you. Useful when you do not want to set a static IP and or have access to the router.

You will need an email account for this to work. If you choose to use a gmail account you will need to go here to set up your account to be less secure. This account can not use two factor authentication. SO you may want to set up a an account for testing…

Set this up as a CRON job at boot or a systemd app.

#! /usr/bin/python
# I use VIM and I use spaces...
import smtplib
import socket
import datetime, time
import sys

failed = 1
while(failed):
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        my_ip = s.getsockname()[0]
        print 'my_ip is: ', my_ip
        s.close()
        failed = 0
    except socket.error as msg:
        print sys.exc_info()[0]
    except:
        print 'error'
    time.sleep(30)

sender = "you@gmail.com"               # Your testing gmail account in quotes.
recipient = "sendTo@abc.com"           # The address sending to in quotes
password = "TestingAccountPassword"    # The testing account password in quotes
subject = "Python IP"
text = " My IP is: %s" % (my_ip)

msg = "From: %s \nTo: %s \nSubject: %s \n\n %s" % (sender, recipient, subject, text)

try:
    smtp_server = smtplib.SMTP_SSL("smtp.gmail.com", 465)
    smtp_server.login(sender, password)
    smtp_server.set_debuglevel(True)
    smtp_server.sendmail(sender, [recipient], msg)
    smtp_server.close()
    #~ print msg
except smtplib.SMTPException:
    print "Error:  unable to send email"
ip_email.txt · Last modified: 2017/12/26 02:34 by mackrackit