Advertisement
Guest User

[Python3] Internal IP sender

a guest
Jul 25th, 2014
502
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.66 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # Author: Jen [jen.development@gmail.com]
  4. # Checks the 'internal' IP of the device. If it has changed since the last
  5. # time it was checked, sends an email to a mail address with the new IP.
  6. #
  7. # It was originally designed to use with the RaspberryPi and be able to connect
  8. # to the device in LAN.
  9.  
  10. import smtplib
  11. import subprocess
  12. import time
  13.  
  14. def GetInternalIP(interface):
  15.     output=subprocess.check_output(["ifconfig", interface])
  16.     output=output.decode('utf-8')
  17.    
  18.     # Parse ifconfig output
  19.     lines=output.split("\n")
  20.     ipAddr=lines[1].strip().split("  ")[0].split(":")[1]
  21.     return ipAddr
  22.  
  23.  
  24. def SendMail():
  25.     dateAndTime=time.strftime("%A, %d %m %Y %H:%M:%S (%Z)", time.localtime())
  26.  
  27.     subject="Raspberry Pi event [{}]".format(ipAddr)
  28.     body="Current raspberry IP is: {}\n\n\n{}".format(ipAddr, dateAndTime) 
  29.  
  30.     msg="From: {0}\nTo: {1}\nSubject: {2}\n\n{3}".format(fromAddr, toAddr[0], subject, body)   
  31.    
  32.     # Create SMTP Object
  33.     smtpObj=smtplib.SMTP(smtpServer, smtpPort)
  34.  
  35.     smtpObj.ehlo() # Identify client
  36.     smtpObj.starttls()
  37.     smtpObj.ehlo() # Identify client under TLS
  38.  
  39.     smtpObj.login(smtpUser, smtpPass)
  40.  
  41.     smtpObj.sendmail(fromAddr, toAddr, msg)
  42.     smtpObj.quit()
  43.     return
  44.  
  45.  
  46. interface="wlan0"
  47. prevIP=None #NO TOCAR
  48.  
  49. smtpServer="smtp.gmail.com"
  50. smtpPort=587
  51. smtpUser="tu.correo@gmail.com"
  52. smtpPass="contraseñadelcorreo"
  53.  
  54. fromAddr="<tu.correo@gmail.com>"
  55. toAddr=["<tu.correo@gmail.com>"]
  56.  
  57. # Workaround to gain time while some necessary network resources are being prepared
  58. time.sleep(30)
  59.  
  60. while True:
  61.     ipAddr=GetInternalIP(interface)
  62.     if ipAddr != prevIP:
  63.         SendMail()
  64.         prevIP=ipAddr  
  65.     time.sleep(900) # 15 minutes
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement