#!/usr/bin/python
import urllib2
import re
import sys
import string
import popen2
from BeautifulSoup import BeautifulSoup

url = 'http://192.168.0.1/DHCPTable.asp'
user = "admin"
passwd = "xxxxxx"
domain = "hemma.tobbe.nu"

try:
	authinfo = urllib2.HTTPBasicAuthHandler()
	authinfo.add_password(realm="WRT54GL",user=user,passwd=passwd,uri=url)
	opener = urllib2.build_opener(authinfo)
	urllib2.install_opener(opener)
	req = urllib2.Request(url)
	handle = urllib2.urlopen(req)
	data = handle.read()
	handle.close()
	soup = BeautifulSoup(data)
	script = str(soup('script')[17])
	pattern = re.compile('var table = new Array\((.*?)\);',re.S)
	arr = pattern.findall(script)
	zon = []
	if len(arr) > 0:
		arr = arr[0].split('\n')
		for row in arr:
			if len(row) > 0:
				arow = row
				pattern2 = re.compile("^[ ,]*'([^']*)',\s*'([^']*)'")
				matches = pattern2.findall(row)
				host,ip = matches[0]
				if host != '&nbsp;':
					zon.append((host,ip))
	s = ''
	for (host,ip) in zon:
		s += 'update delete %s.%s A\n' % (host,domain)
		s += 'update add %s.%s 3600 A %s\n' %(host,domain,ip)
		s += 'send\n'
		rev = string.joinfields([a for a in reversed(ip.split('.'))],'.')
		s += 'update delete %s.in-addr.arpa\n' % rev
		s += 'update add %s.in-addr.arpa 3600 PTR %s.%s.\n' % (rev,host,domain)
		s += 'send\n'
	tupl = popen2.popen3('nsupdate')
	outfd,infd,errfd = tupl
	infd.write(s)
	infd.close()
#	print outfd.read()
#	print errfd.read()
	outfd.close()
	errfd.close()
except IOError, e:
	print 'Unable to open "%s"' % url
	
