Sipdroid's Blog

dyndns python script auto update

Posted in python by sipdroid on February 5, 2010

#!/usr/bin/python

import sys,re,base64,string,cookielib, urllib, urllib2,httplib

login = 'xxx'
password = 'xxx'

hostlist='xxx.xxx.xxx'  <--- your host name

m=urllib.urlopen('<a href="http://checkip.dyndns.org/')">http://checkip.dyndns.org/')</a>
if m :
content = m.read()
else :
print ' could not connect to external network '
sys.exit(1)

match = re.search(r'<body>Current IP Address: (\S)+</body>',content)
if not match :
print ' could not get my external ip address'
sys.exit(2)

ipaddress = match.group(0)
print 'our external IP address is :'+ ipaddress

updatehost = "members.dyndns.org"
fakeagent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)"
updatepage = "/nic/update"
updateprefix = updatepage + "?system=custom&hostname="
updatesuffix = '&myip='+ipaddress

h2 = httplib.HTTPS(updatehost)
h2.putrequest("GET", updateprefix + hostlist + updatesuffix)
h2.putheader("HOST", updatehost)
h2.putheader("USER-AGENT", fakeagent)
authstring = base64.encodestring(login + ":" + password)
authstring = string.replace(authstring, "12", "")
h2.putheader("AUTHORIZATION", "Basic " + authstring)
h2.endheaders()

errcode, errmsg, headers = h2.getreply()

# try to get the html text
try:
fp = h2.getfile()
httpdata = fp.read()
fp.close()
except:
httpdata = "No output from http request."
fp.close()

print httpdata