I use DynDns to map my ISP provided dynamic IP to a static hostname. For some reason, the DynDns provided update clients don’t always work for me and often leave my hostname pointing to a dead or (worse) someone else’s IP. I decided to take matter into my own hands and write a script that would email me my IP whenever my DHCP lease expired and my ISP issued me a fresh one. This would ensure I know how to reach back home, even if my hostname was pointing to an old IP.
While going through the DynDns API, I realized it was trivial to update the hostname as well, essentially replicating the functionality of the aforementioned client(s). So I decided to add that as well.
I know this functionality can be replicated via curl + sendmail, but Python is my tool of choice, so just live with it. Without further ado, here’s the script, with an explanation afterwards.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | #!/usr/bin/env python # encoding: utf-8 """ Script to email IP whenever it changes. Also updates DynDns hostname. Version 1.0 Created by Kunal Dua on 2010-05-10 http://www.kunaldua.com/blog/?p=360 This program is free software; you may redistribute it and/or modify it under the same terms as Python itself. """ def send_mail(subject, content): import smtplib from email.mime.text import MIMEText SERVER = "smtpserver" PORT = 587 #Use 25 if this doesn't work USER = "username" PASS = "password" FROM = "IPBot <mail@example.com>" TO = "user+folder@example.com" SUBJECT = subject TEXT = content message = MIMEText(TEXT) message['Subject'] = SUBJECT message['From'] = FROM message['To'] = TO server = smtplib.SMTP(SERVER, PORT) server.login (USER, PASS) server.sendmail(FROM, TO, message.as_string()) server.quit() def update_dyndns(theip): USERNAME = 'username' PASSWORD = 'password' HOSTNAME = 'example.dyndns.org' theurl = 'https://%s:%s@members.dyndns.org/nic/update?hostname=%s&myip=%s&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG' % (USERNAME, PASSWORD, HOSTNAME, theip) import urllib conn = urllib.urlopen(theurl) #print conn.read() conn.close() if __name__ == '__main__': import urllib2, re conn = urllib2.urlopen('http://checkip.dyndns.com/') data = conn.read() conn.close() m = re.search('([0-9]*)(\.)([0-9]*)(\.)([0-9]*)(\.)([0-9]*)', data) currip = m.group(0) lastfile = "lastip.txt" allfile = "history.txt" theipfile = open(lastfile,"r") lastip = theipfile.read() theipfile.close() if lastip == currip: #print "no change needed" exit() else: histfile = open(allfile, "a") import datetime thenow = datetime.datetime.now().ctime() histfile.write("%s %s\n" % (thenow, currip)) histfile.close() theipfile = open(lastfile,"w") theipfile.write(currip) theipfile.close() send_mail(currip, '') update_dyndns(currip) |
- Lines 17-22 and 39-41 replace with your email and DynDns settings respectively.
- Line 22 – My email provider supports redirecting mails to a folder by simply adding the name of the folder before @ sign. For example user+ipupdates@example.com will deliver mail in folder ipupdates of user@example.com. If your email provider supports this, it’s a useful trick to prevent these mails from cluttering up your inbox. If not, simply enter your regular email address.
- Lines 60-61 initialize 2 files that I use. One is to store the current IP (or the last known IP) and the other is a history of all IP changes. The former is used to compare if the IP has changed since the script was last run and thus if an email needs to be sent + DynDns updated. The latter is not really needed for the script to function properly, and is used to maintain a log of all IP changes – because you can!
- Line 78 – By default, the subject of the mail is the IP and the body/ text is blank. Feel free to obfuscate your IP if you feel paranoid about sending it in clear text or write sweet nothings to yourself in the body.
- Note: Before you run this script for the first time, create an empty file called lastip.txt in the same directory as the script or the script will fail. I know I could write a trivial check for this, but I leave that as an exercise for the reader.
Recommended frequency of running this job via cron/ launchd is 10 minutes.
Update: (May 27) I am pretty sure the DynDns API is broken in some way because I can’t get it to update even with this script. The email part is working pretty good for me though!
Related posts:
Pingback: Tweets that mention Get email updates when your IP changes/ Python DynDns update client « Kunal Dua -- Topsy.com
Pingback: Deep Kalra, Kunal Bajaj, PN Vi… | smsyellowpages.net
Pingback: How To Set Up A Home Server | www.avehot.com
I will recommend not to wait until you get enough amount of cash to order all you need! You should take the mortgage loans or just college loan and feel comfortable
Pingback: Apache? Dyndns? Configurations? | High Speed Routers
I tried this, but there seems to be a problem with urllib with the colon in the address, I was wondering if you know of a way to get around that. It seems to take whatever is after the colon as the port.
Thanks for this! I had to make a few changes. Specifically, to get the authorization right, I removed the username:password@ section, and instead it looks like:
def update_dyndns(theip):
theurl = ‘https://members.dyndns.org/nic/update?hostname=%s&myip=%s&wildcard=NOCHG&mx=NOCHG&backmx=NOCHG‘ % (HOSTNAME, theip)
#create the credential file
auth_handler = urllib2.HTTPBasicAuthHandler()
auth_handler.add_password(realm=’DynDNS API Access’,
uri=’https://members.dyndns.org/nic/update’,
user=USERNAME,
passwd=PASSWORD)
opener = urllib2.build_opener(auth_handler)
# …and install it globally so it can be used with urlopen.
urllib2.install_opener(opener)
req = urllib2.Request(theurl)
req.add_header(‘User-agent’, ‘your-user-agent-here’)
conn = urllib2.urlopen(req)
#print conn.read()
return conn
Great write-up, but that wouldn’t really to make use of my router ip, any hints?
ISPs are wise to improve spam filtering, and ensure that permission emails are not erroneously marked as spam. Consumers have a plethora of providers to choose from and will stray from those who do not effectively filter messages.
I would like to thnkx for the efforts you’ve put in writing this website. I’m hoping the same high-grade website post from you in the upcoming also. In fact your creative writing skills has encouraged me to get my own web site now. Really the blogging is spreading its wings quickly. Your write up is a good example of it.
Oh my goodness! a tremendous article dude. Thanks However I’m experiencing situation with ur rss . Don’t know why Unable to subscribe to it. Is there anyone getting similar rss drawback? Anybody who knows kindly respond. Thnkx
Somebody essentially help to make critically posts I’d state. That is the first time I frequented your website page and so far? I amazed with the analysis you made to create this particular post extraordinary. Wonderful activity!
This website online can be a walk-via for the entire information you wanted about this and didn’t know who to ask. Glimpse right here, and you’ll positively uncover it.
Great blog here! Additionally your website a lot up fast! What web host are you the usage of? Can I get your associate hyperlink in your host? I wish my web site loaded up as fast as yours lol.
An impressive share, I simply given this onto a colleague who was doing a little evaluation on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying more on this topic. If potential, as you change into expertise, would you mind updating your blog with extra details? It is highly useful for me. Large thumb up for this weblog put up!
I’m extremely impressed with your writing talents as neatly as with the format on your weblog. Is that this a paid theme or did you customize it your self? Either way keep up the nice quality writing, it is rare to look a great weblog like this one these days.
Once more big piece thanks tons for sharing, keep me posted I’ll be interpretation much of your posts in the later!
hello!,I love your writing so so much! proportion we keep up a correspondence more approximately your post on AOL? I need an expert in this house to resolve my problem. Maybe that is you! Taking a look forward to look you.
Hello very nice website!! Man .. Beautiful .. Amazing .. I’ll bookmark your site and take the feeds also…I am happy to seek out so many useful information right here in the publish, we want develop extra techniques on this regard, thank you for sharing.
hallo people!! Super site!
What’s Taking place i’m new to this, I stumbled upon this I’ve found It absolutely useful and it has aided me out loads. I’m hoping to contribute & assist other users like its aided me. Good job.
I used to be more than happy to search out this web-site.I needed to thanks to your time for this glorious learn!! I undoubtedly having fun with every little little bit of it and I have you bookmarked to check out new stuff you weblog post.
Heya i am for the first time here. I came across this board and I to find It truly useful & it helped me out a lot. I’m hoping to give one thing again and aid others like you helped me.
I’m impressed, I must say. Really hardly ever do I encounter a weblog that’s each educative and entertaining, and let me let you know, you’ve got hit the nail on the head. Your idea is outstanding; the difficulty is one thing that not enough persons are speaking intelligently about. I’m very completely satisfied that I stumbled across this in my seek for one thing regarding this.
I’ve been exploring for a little bit for any high-quality articles or blog posts in this kind of space . Exploring in Yahoo I ultimately stumbled upon this website. Reading this info So i’m happy to exhibit that I have an incredibly just right uncanny feeling I came upon exactly what I needed. I most without a doubt will make sure to do not forget this site and give it a look regularly.
I’ve recently started a blog, the info you provide on this site has helped me tremendously. Thanks for all of your time & work.
There are actually a whole lot of details like that to take into consideration. That is a great level to deliver up. I provide the thoughts above as general inspiration however clearly there are questions like the one you carry up the place an important thing shall be working in honest good faith. I don?t know if best practices have emerged round issues like that, however I am certain that your job is clearly recognized as a fair game. Each girls and boys really feel the affect of just a moment’s pleasure, for the rest of their lives.