#!/usr/bin/python
"""

8 Oct: cpbl: fixed the Internet routine (the web site changed, function returned nothing, etc)

2 Oct 2006: cpbl:

Pulled three scripts off the web: send mail using an external smtp
server; find local interface's IP address; find external apparent
Internet IP address.  Useful for putting as a startup script on a
server that is under DHCP.

Save this file as emailMyIP.py and include below the full path to it along with its name

To install in rc.d startup, have it email your IP and use (Debian/Ubuntu):

sudo update-rc.d -f path_to_my_script.py start 99 2 3 4 5 .  

     where
     - start is the argument given to the script (start, stop).
     - 99 is the start order of the script (1 = first one, 99= last one)
     - 2 3 4 5 are the runlevels to start

     Dont forget the dot at the end
     More info in /etc/rcS.d/README

"""
import smtplib
from email.MIMEText import MIMEText

def sendTextMail(to,sujet,text,server="smtp.interchange.ubc.ca",fro = "My automatic server <cpbl@freeshell.org>"):
    mail = MIMEText(text)
    mail['From'] = fro
    mail['Subject'] =sujet
    mail['To'] = to
    smtp = smtplib.SMTP(server)
    smtp.sendmail(fro, [to], mail.as_string())
    smtp.close()


import socket
import fcntl
import struct

def get_ip_address(ifname): # Unix only :(
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

#>>> get_ip_address('lo')
#'127.0.0.1'
#
#>>> get_ip_address('eth0')
#'38.113.228.130'


# This is cool! If you're behind a NAT router, find your external/visible IP address (it woudln't be unique)...  
def get_internet_address():
    from httplib import HTTPConnection
    from xml.dom.ext.reader.Sax import FromXmlStream
    conn = HTTPConnection('www.showmyip.com')
    conn.request('GET', '/xml/')
    doc = FromXmlStream(conn.getresponse())
    #print doc.getElementsByTagName('ip')[0].firstChild.data
    conn.close()
    return(doc.getElementsByTagName('ip')[0].firstChild.data)

localIP= get_ip_address('eth0')
internetVis=get_internet_address()

print "%s\nLocal interface is %s\nThe internet sees me as %s\n"%(localIP,localIP,internetVis)

sendTextMail("cpbl@interchange.ubc.ca","Server booted: ip address assignment","%s\nLocal interface is %s\nThe internet sees me as %s\n"%(localIP,localIP,internetVis))
 
