Wednesday, December 8, 2010

A little Python script

In our OPS535 class, we need to extract the records from a wiki page and generate a zone file. Normally, bash script is the choice for such a job. You use wget to download the file. Then you grep, cut, and output to another file. (You can download the page manually because the contents changes from time to time.)

Since I'm new in Python, I decide to do a little practice in Python scripting. There is a nice feature in Python in dealing with web pages. You don't have to download the page. You can just open it, process it and then write your output to a local file. You need import a package called urllib for that purpose. Anyway, below is the script I wrote for the task.

#!/usr/bin/python
'''generate a root.zone fine from the wiki page of DNS registration'''
import urllib
url = "http://zenit.senecac.on.ca/wiki/index.php/Domainreg"
#open the webpage and read the registration info into a list and then close the webpage
webpage = urllib.urlopen(url)
lst = []
lst2 = []
for line in webpage:
    line = line.strip()
    if line.startswith("</td><td>"):
        lst.append(line[9:].strip())
webpage.close()
#read the useful items from lst to lst2
for i in range(0,len(lst)):
    if i % 5 == 0 or i % 5 == 2 or i % 5 == 3:
        if lst[i] != '':
            lst2.append(lst[i])
#now generate root.zone file
output = open("root.zone", "w")
output.write("$TTL 86400\n")
output.write("@    IN   SOA  host.mydomain.com.   root.host.mydomain.com. (\n")
output.write("                42    ; serial\n")
output.write("                3H    ; refresh\n")
output.write("                15M    ; retry\n")
output.write("                1W    ; expiry\n")
output.write("                1D )    ; minimum\n")
output.write("@    IN   NS    host.mydomain.com.\n")
num = len(lst2)/3
for i in range(0, num):
    output.write(lst2[3*i])
    output.write(".        IN    NS    ")
    output.write(lst2[3*i + 2])
    output.write(".\n")
    output.write(lst2[3*i + 2])
    output.write(".    IN    A    ")
    output.write(lst2[3*i + 1])
    output.write("\n")
output.close()

No comments:

Post a Comment