Inviare email con il proprio IP esterno

prima stesura di uno script che controlla l’ IP esterno (WAN) e, se variato, invia una email con i dati.
ho modificato uno script di Robert Dempsey.

#!/usr/bin/env python
# encoding: utf-8

import os
import sys
import json
import smtplib
import urllib2
from email import encoders
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart

COMMASPACE = ', '
SMARTHOST = 'INDIRIZZO SMTP'
PORT = 587
SENDER = 'SENDER LOGIN'
PASSWORD = 'SENDER PASSWORD'
RECIPIENTS = ['INDIRIZZI']
MAIL_SUBJECT = 'SOMETHING'
IFCONFIGME = 'http://ifconfig.me'
IPFILE = '/path/to/some/file'

def main():
    req = urllib2.Request(IFCONFIGME + '/all.json')
    try:
        res = urllib2.urlopen(req)
        data = res.read()
        new_json = json.loads(data)
        json.dumps(new_json)
        if os.path.exists(IPFILE):
            with open(IPFILE, 'r') as f:
                old_json = json.load(f)
    except urllib2.URLError as e:
        print e.reason
        raise
    except urllib2.HTTPError as e:
        print e.code
        print e.read()
        raise
    except:
        print 'Errore'
        raise

    try:
        old_json
    except NameError:
        with open(IPFILE, 'w') as f:
            json.dump(new_json, f)
    else:
        if new_json['ip_addr'] == old_json['ip_addr']:
            print 'IP non cambiato'
            sys.exit()

    # Create the enclosing (outer) message
    outer = MIMEMultipart()
    outer['Subject'] = MAIL_SUBJECT
    outer['To'] = COMMASPACE.join(RECIPIENTS)
    outer['From'] = SENDER
    outer.preamble = 'You will not see this in a MIME-aware mail reader.\n'

    body = MIMEText('Nuovo indirizzo IP: ' + new_json['ip_addr'] \
        + '\n\n\n JSON:\n' + json.dumps(new_json, indent=4))
    outer.attach(body)

    # List of attachments
    #attachments = ['FULL PATH TO ATTACHMENTS HERE']
    attachments = []

    # Add the attachments to the message
    for file in attachments:
        try:
            with open(file, 'rb') as fp:
                msg = MIMEBase('application', "octet-stream")
                msg.set_payload(fp.read())
            encoders.encode_base64(msg)
            msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
            outer.attach(msg)
        except:
            print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
            raise

    composed = outer.as_string()

    # Send the email
    try:
        s = smtplib.SMTP(SMARTHOST, PORT)
        s.ehlo()
        #s.starttls()
        #s.ehlo()
        s.login(SENDER, PASSWORD)
        s.sendmail(SENDER, RECIPIENTS, composed)
        s.quit()
        print("Email sent!")
    except:
        print("Unable to send the email. Error: ", sys.exc_info()[0])
        raise

if __name__ == '__main__':
    main()

Lascia un commento

Inserisci i tuoi dati qui sotto o clicca su un'icona per effettuare l'accesso:

Logo WordPress.com

Stai commentando usando il tuo account WordPress.com. Chiudi sessione / Modifica )

Foto Twitter

Stai commentando usando il tuo account Twitter. Chiudi sessione / Modifica )

Foto di Facebook

Stai commentando usando il tuo account Facebook. Chiudi sessione / Modifica )

Google+ photo

Stai commentando usando il tuo account Google+. Chiudi sessione / Modifica )

Connessione a %s...