Created
October 13, 2010 15:14
-
-
Save EnigmaCurry/624233 to your computer and use it in GitHub Desktop.
IP Address change notifier
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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
__author__ = "Ryan McGuire ([email protected])" | |
__date__ = "Wed Sep 1 22:05:31 2010" | |
#Check the current external IP address | |
#If it has changed, email me the new one (via cron) | |
#Update the dynamic DNS provider | |
#This is used on my router, where the real external IP address | |
#is assigned directly to my NIC. This script won't work on a NAT'd box. | |
import socket | |
import fcntl | |
import struct | |
import sys | |
import urllib2 | |
last_ip_file = "/storage/var/lib/ip_checker/last_ip.txt" | |
dyndns_update = "http://USERNAME:[email protected]/nic/update?hostname=YOUR_DYNAMIC_HOSTNAME" | |
def get_ip_address(ifname): | |
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]) | |
def check_ip_change(): | |
current_ip = get_ip_address("red") | |
with open(last_ip_file) as f: | |
last_ip = f.read() | |
if current_ip != last_ip: | |
#The IP changed | |
with open(last_ip_file, "w") as f: | |
f.write(current_ip) | |
#Email the new IP (via cron) | |
print("Sentry external IP address changed: {ip}".format(ip=current_ip)) | |
#Update the dyndns record | |
urllib2.urlopen(dyndns_update).read() | |
return 1 | |
return 0 | |
if __name__ == '__main__': | |
sys.exit(check_ip_change()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment