brand new to python

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • richard.hubbell@gmail.com

    #1

    brand new to python

    I am sure this is old news, the syntax of python is crazy to me.
    There I said it, I'm sure I'll get over it or around it.

    I was trying to make a whois script work and was unable.

    May be someone with lint-like eyes can tell what's wrong.

    Using xemacs I had hoped that python mode would do more
    for syntax problems, maybe I'm just not using python mode
    correctly in xemacs??

    ../whois.py yahoo.com
    File "./whois.py", line 117
    class DomainRecord:
    ^
    SyntaxError: invalid syntax


    #!/usr/bin/env python


    #usage: %(progname)s [--test] [domain...]

    #Version: %(version)s

    #Contacts the NetworkSolution s whois database for each domain and
    displays
    #the result.

    #public methods:

    # def whois(domainnam e, whoisserver=Non e, cache=0)
    # raises NoSuchDomain if the domain doesn't exist.

    # return the result of contacting NetworkSolution s

    #def ParseWhois(page )
    # returns a DomainRecord object that contains a parsed
    #version of the information contained in 'page'.

    #class DomainRecord:
    # self.domain -- name of the domain
    #self.domainid -- domainid for this domain
    # self.created -- date in which the domain was created
    # self.lastupdate d -- date in which the domain was last updated.
    # self.expires -- date in which the domain expires
    # self.databaseup dated -- date in which the database was last
    updated.
    # self.servers -- list of (hostname, ip) pairs of the
    # nameservers.
    # self.registrant -- name of the person or organization that
    # registered the domain.
    # self.registrant _address -- address of the person or organization
    that
    # registered the domain.
    # self.contacts -- dictionary of contacts###
    ##
    #
    #"""

    #_version = "1.0"

    import os, sys, string, time, getopt, socket, select, re

    NoSuchDomain = "NoSuchDoma in"

    def whois(domainnam e, whoisserver=Non e, cache=0):
    if whoisserver is None:
    whoisserver = "whois.networks olutions.com"

    if cache:
    fn = "%s.dom" % domainname
    if os.path.exists( fn):
    return open(fn).read()

    page = _whois(domainna me, whoisserver)

    if cache:
    open(fn, "w").write(page )

    return page

    def _whois(domainna me, whoisserver):
    s = None

    ## try until we are connected

    while s == None:
    try:
    s = socket.socket(s ocket.AF_INET, socket.SOCK_STR EAM)
    s.setblocking(0 )
    try:
    s.connect(whois server, 43)
    except socket.error, (ecode, reason):
    if ecode in (115, 150):
    pass
    else:
    raise socket.error, (ecode, reason)
    ret = select.select([s], [s], [], 30)

    if len(ret[1]) == 0 and len(ret[0]) == 0:
    s.close()
    raise TimedOut, "on connect "
    s.setblocking(1 )

    except socket.error, (ecode, reason):
    print ecode, reason
    time.sleep(10)
    s = None

    s.send("%s \n\n" % domainname)
    page = ""
    while 1:
    data = s.recv()
    if not data: break

    page = page + data

    s.close()

    if string.find(pag e, "No match for") != -1:
    raise NoSuchDomain, domainname

    if string.find(pag e, "No entries found") != -1:
    raise NoSuchDomain, domainname

    if string.find(pag e, "no domain specified") != -1:
    raise NoSuchDomain, domainname

    if string.find(pag e, "NO MATCH") != -1:
    raise NoSuchDomain, domainname
    return page

    ##
    ##
    ----------------------------------------------------------------------
    ##

    class DomainRecord:
    def __init__(self, domain):
    self.domain = domain
    self.domainid = None
    self.created = None
    self.lastupdate d = None
    self.expires = None
    self.databaseup dated = None
    self.servers = None
    self.registrant = None
    self.registrant _address = None
    self.contacts = {}

    def __str__(self):
    return "%s (%s): (created:%s) (lastupdated:%s )
    (databaseupdate d:%s) (servers:%s) (registrant:%s) (address:%s)
    (contacts:%s)" % (self.domain, self.domainid, self.created,
    self.lastupdate d, self.databaseup dated, self.servers, self.registrant ,
    repr(self.regis trant_address), self.contacts)


    ##
    ##
    ----------------------------------------------------------------------
    ##

    def _ParseContacts_ RegisterCOM(pag e):
    contactDict = {}
    parts = re.split("((?:( ?:Administrativ e|Billing|Techn ical|Zone)
    Contact,?[ ]*)+:)\n", page)

    contacttypes = None
    for part in parts:
    if string.find(par t, "Contact:") != -1:
    if part[-1] == ":": part = part[:-1]
    contacttypes = string.split(pa rt, ",")
    continue
    part = string.strip(pa rt)
    if not part: continue

    record = {}

    lines = string.split(pa rt, "\n")
    m = re.search("(.+) (.+@.+)", lines[0])
    if m:
    record['name'] = string.strip(m. group(1))
    record['handle'] = None
    record['email'] = string.lower(st ring.strip(m.gr oup(2)))

    flag = 0
    phonelines = string.strip(li nes[1])
    record['phone'] = phonelines
    record['address'] = []

    for contacttype in contacttypes:
    contacttype = string.lower(st ring.strip(cont acttype))
    contacttype = string.replace( contacttype, " contact", "")
    contactDict[contacttype] = record

    return contactDict



    def ParseWhois_Regi sterCOM(page):

    m = re.search("Doma in Name: (.+)", page)
    domain = m.group(1)
    rec = DomainRecord(do main)

    m = re.search("Reco rd last updated on.*: (.+)", page)
    if m: rec.lastupdated = m.group(1)

    m = re.search("Crea ted on.*: (.+)", page)
    if m: rec.created = m.group(1)

    m = re.search("Expi res on.*: (.+)", page)
    if m: rec.expires = m.group(1)


    m = re.search("Regi strant:", page)
    if m:
    i = m.end()
    m = re.search("\n\n ", page[i:])
    j = m.start()
    registrant = string.strip(pa ge[i:i+j])
    lines = string.split(re gistrant, "\n")
    registrant = []
    for line in lines:
    line = string.strip(li ne)
    if not line: continue
    registrant.appe nd(line)
    rec.registrant = registrant[0]
    rec.registrant_ address = string.join(reg istrant[1:], "\n")

    m = re.search("(.+) \((.+)\)$", rec.registrant)
    if m:
    rec.registrant = m.group(1)
    rec.domainid = m.group(2)

    m = re.search("Doma in servers in listed order:\n\n", page)
    if m:
    i = m.end()
    m = re.search("\n\n ", page[i:])
    j = m.start()
    servers = string.strip(pa ge[i:i+j])
    lines = string.split(se rvers, "\n")
    servers = []
    for line in lines:
    parts = string.split(st ring.strip(line ))
    if not parts: continue
    servers.append( parts[0], parts[1])
    rec.servers = servers

    m =
    re.search("((?: (?:Administrati ve|Billing|Tech nical|Zone) Contact,?[
    ]*)+:)\n", page)
    if m:
    i = m.start()
    m = re.search("Doma in servers in listed order", page)
    j = m.start()
    contacts = string.strip(pa ge[i:j])

    rec.contacts = _ParseContacts_ RegisterCOM(con tacts)

    return rec

    ##
    ##
    ----------------------------------------------------------------------
    ##

    def _ParseContacts_ NetworkSolution s(page):
    contactDict = {}
    parts = re.split("((?:( ?:Administrativ e|Billing|Techn ical|Zone)
    Contact,?[ ]*)+:)\n", page)

    contacttypes = None
    for part in parts:
    if string.find(par t, "Contact:") != -1:
    if part[-1] == ":": part = part[:-1]
    contacttypes = string.split(pa rt, ",")
    continue
    part = string.strip(pa rt)
    if not part: continue

    record = {}

    lines = string.split(pa rt, "\n")
    m = re.search("(.+) \((.+)\) (.+@.+)", lines[0])
    if m:
    record['name'] = string.strip(m. group(1))
    record['handle'] = string.strip(m. group(2))
    record['email'] = string.lower(st ring.strip(m.gr oup(3)))

    flag = 0
    addresslines = []
    phonelines = []
    for line in lines[1:]:
    line = string.strip(li ne)
    if not line:
    flag = 1
    continue
    if flag == 0:
    addresslines.ap pend(line)
    else:
    phonelines.appe nd(line)
    record['phone'] = string.join(pho nelines, "\n")
    record['address'] = string.join(add resslines, "\n")

    for contacttype in contacttypes:
    contacttype = string.lower(st ring.strip(cont acttype))
    contacttype = string.replace( contacttype, " contact", "")
    contactDict[contacttype] = record

    return contactDict

    def ParseWhois_Netw orkSolutions(pa ge):
    m = re.search("Doma in Name: (.+)", page)
    domain = m.group(1)
    rec = DomainRecord(do main)

    m = re.search("Reco rd last updated on (.+)\.", page)
    if m: rec.lastupdated = m.group(1)

    m = re.search("Reco rd created on (.+)\.", page)
    if m: rec.created = m.group(1)

    m = re.search("Data base last updated on (.+)\.", page)
    if m: rec.databaseupd ated = m.group(1)

    m = re.search("Regi strant:", page)
    if m:
    i = m.end()
    m = re.search("\n\n ", page[i:])
    j = m.start()
    registrant = string.strip(pa ge[i:i+j])
    lines = string.split(re gistrant, "\n")
    registrant = []
    for line in lines:
    line = string.strip(li ne)
    if not line: continue
    registrant.appe nd(line)
    rec.registrant = registrant[0]
    rec.registrant_ address = string.join(reg istrant[1:], "\n")

    m = re.search("(.+) \((.+)\)$", rec.registrant)
    if m:
    rec.registrant = m.group(1)
    rec.domainid = m.group(2)

    m = re.search("Doma in servers in listed order:\n\n", page)
    if m:
    i = m.end()
    m = re.search("\n\n ", page[i:])
    j = m.start()
    servers = string.strip(pa ge[i:i+j])
    lines = string.split(se rvers, "\n")
    servers = []
    for line in lines:
    parts = string.split(st ring.strip(line ))
    if not parts: continue
    servers.append( parts[0], parts[1])
    rec.servers = servers

    m =
    re.search("((?: (?:Administrati ve|Billing|Tech nical|Zone) Contact,?[
    ]*)+:)\n", page)
    if m:
    i = m.start()
    m = re.search("Reco rd last updated on", page)
    j = m.start()
    contacts = string.strip(pa ge[i:j])

    rec.contacts = _ParseContacts_ NetworkSolution s(contacts)

    return rec


    ##
    ##
    ----------------------------------------------------------------------
    ##

    def ParseWhois(page ):
    if string.find(pag e, "Registrar. .: Register.com
    (http://www.register.co m)") != -1:
    return ParseWhois_Regi sterCOM(page)
    else:
    return ParseWhois_Netw orkSolutions(pa ge)


    ##
    ##
    ----------------------------------------------------------------------
    ##

    def usage(progname) :
    version = _version
    print __doc__ % vars()

    def main(argv, stdout, environ):
    progname = argv[0]
    list, args = getopt.getopt(a rgv[1:], "", ["help", "version",
    "test"])

    for (field, val) in list:
    if field == "--help":
    usage(progname)
    return
    elif field == "--version":
    print progname, _version
    return
    elif field == "--test":
    test()
    return


    for domain in args:
    try:
    page = whois(domain)
    print page
    except NoSuchDomain, reason:
    print "ERROR: no such domain %s" % domain

    if __name__ == "__main__":
    main(sys.argv, sys.stdout, os.environ)

Working...