Last active
December 29, 2015 11:59
-
-
Save psychok7/7667311 to your computer and use it in GitHub Desktop.
Utility to check changes of Dynamic IP addresses. It emails the user every 6 hours if the IP changes in that period. This is better then having a domain because you computer is a bit more secure since only you know the IP to access it.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import subprocess | |
import time | |
import smtplib | |
import string | |
# Author Nuno Khan | |
# Utility to check dynamic ip addresses | |
def save_new_Ip(p): | |
ip="" | |
f = open('ip.log', 'a') | |
for line in p.stdout.readlines(): | |
ip= ip+line | |
f.write(ip) | |
print ("You IP address is {ip}").format(**locals()) | |
f.close() | |
return ip.strip() | |
def compare_ip(): | |
fileHandle = open ( 'ip.log',"r" ) | |
lineList = fileHandle.readlines() | |
fileHandle.close() | |
if lineList[-2] != lineList[-1] : | |
return True | |
else: | |
return False | |
def sendMail(TO,text): | |
username="xxx" | |
password="xxx" | |
HOST = "smtp.gmail.com:587" | |
SUBJECT = "Your IP address changed" | |
FROM = "Khan Desktop" | |
BODY = string.join(("From: %s" % FROM,"To: %s" % TO,"Subject: %s" % SUBJECT ,"",text), "\r\n") | |
server = smtplib.SMTP(HOST) | |
try: | |
server.set_debuglevel(False) | |
# identify ourselves, prompting server for supported features | |
server.ehlo() | |
# If we can encrypt this session, do it | |
if server.has_extn('STARTTLS'): | |
server.starttls() | |
server.ehlo() # re-identify ourselves over TLS connection | |
server.login(username,password) | |
server.sendmail(FROM, [TO], BODY) | |
finally: | |
server.quit() | |
def check_ip(): | |
print ("Checking IP address") | |
command="wget -q -O - checkip.dyndns.org|sed -e 's/.*Current IP Address: //' -e 's/<.*$//'" | |
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) | |
new_ip=save_new_Ip(p) | |
if(compare_ip()): | |
sendMail("[email protected]",new_ip) | |
retval = p.wait() | |
print ("In 6 hours the IP address will be checked again") | |
def main(): | |
while (True): | |
re_check = 21600 # 6 hours | |
check_ip() | |
time.sleep(re_check) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment