YoungJules

PyDynDns

Jan 4th, 2012
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.06 KB | None | 0 0
  1. #! /usr/bin/python
  2.  
  3. import os
  4. import time
  5. import urllib2
  6. import smtplib
  7. from email.MIMEMultipart import MIMEMultipart
  8. from email.MIMEBase import MIMEBase
  9. from email.MIMEText import MIMEText
  10. from email.Utils import COMMASPACE, formatdate
  11. from email import Encoders
  12.  
  13. def check_in():
  14.  
  15.     fqn = os.uname()[1]
  16.     tries = 0
  17.     success = False
  18.     while (not success or tries > 5):
  19.         try:
  20.             ext_ip = urllib2.urlopen('http://whatismyip.org').read()
  21.             success = True
  22.         except:
  23.             tries += 1
  24.             print "tries: %d, sleeping for 10 secs" % tries
  25.             time.sleep(10)
  26.                
  27.     #print ("Asset: %s " % fqn, "Checking in from IP#: %s " % ext_ip)
  28.     return fqn, ext_ip
  29.  
  30. def sendMail(to, fro, subject, text, files=[],server="localhost"):
  31.     assert type(to)==list
  32.     assert type(files)==list
  33.  
  34.  
  35.     msg = MIMEMultipart()
  36.     msg['From'] = fro
  37.     msg['To'] = COMMASPACE.join(to)
  38.     msg['Date'] = formatdate(localtime=True)
  39.     msg['Subject'] = subject
  40.  
  41.     msg.attach( MIMEText(text) )
  42.  
  43.     for file in files:
  44.         part = MIMEBase('application', "octet-stream")
  45.         part.set_payload( open(file,"rb").read() )
  46.         Encoders.encode_base64(part)
  47.         part.add_header('Content-Disposition', 'attachment; filename="%s"'
  48.                        % os.path.basename(file))
  49.         msg.attach(part)
  50.  
  51.     smtp = smtplib.SMTP(server)
  52.     smtp.sendmail(fro, to, msg.as_string() )
  53.     smtp.close()
  54.  
  55.  
  56. fqn, ext_ip = check_in()
  57.  
  58. print "FQN: %s" % fqn
  59. print "Ext IP: %s" % ext_ip
  60. filedata = ""
  61. if (os.path.exists('ipaddr.txt')):
  62.     f = open('ipaddr.txt', 'r')
  63.     filedata = f.read()
  64.     f.close()
  65. if (str(filedata) == ext_ip):
  66.     print "ip match!"
  67. else:
  68.     print "IPs don't match, updating ipaddr.txt..."
  69.     f = open('ipaddr.txt', 'w')
  70.     f.write(ext_ip)
  71.     f.close()
  72.     print "...sending mail..."
  73.     sendMail(['Jules <[email protected]>'],'YoungJules <[email protected]>','Hello from your server!','FQN: %s, IP address: %s' % (fqn, ext_ip),[])
  74.     print "...all done!"
Advertisement
Add Comment
Please, Sign In to add comment