473,791 Members | 3,229 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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)

Jul 18 '05 #1
0 1437

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2130
by: William Ryan | last post by:
I was at the VS.NET product launch and they discussed this in depth. NO, they aren't dropping .NET. THey are just changing the branding. .NET Server for instance sounded Lame and the focus groups hated it. Wait until the Hears Windows 2003 Server which is what you have to call it now. Who knows what they'll finally call it (Lord knows that Dillweed at Sun hopped all over Hailstorm) but it's a Rose by any other name thing. Remember...
2
2205
by: noone | last post by:
Hello all, I am absolutely brand new to perl, but I understand that it is a very important aspect of web development to create dynamic web pages. I am kind of short on money, being a college student and all, and I have looked at several bookstores for books about perl and: 1. I don't know what topics I should be looking for to learn the basics of the perl language. 2. Most of the books are too much for me to shell out right now...
10
2472
by: Harry Slaughter | last post by:
I've got a client who wants to see some immediate results on a brand new website. within a week, they'd like to see the following: 1) basic user authentication (using php sessions/cookies to maintain authentication) 2) some basic content (text, photos, audio) uploading mechanism 3) basic content browsing in a somewhat neatly formatted presentation knowing how quickly they wanted something they could look at, i initially suggested...
0
1735
by: W. D. | last post by:
Hi, I am new to Access. Just installed on Win98 SE. I fire it up and get errors complaining about registry entries: MsInputMaskBuilder MSODBCConnectStrBuilder MSLinkChildFieldsBuilder
1
1187
by: Miles Keaton | last post by:
I'm a brand new PostgreSQL user -- just started today (though I've used MySQL for years). Should I just start learning with version 8, since I'm sure I won't launch any real live public projects with PostgreSQL for another few months? Any estimate when 8.0.0 will be final & production-ready? Thanks!
10
1120
by: agent E 10 | last post by:
Hi, I'm brand new to programming. Have any suggestions? I'm young. Was it a good idea to start with python? I was planning on creating a very simple program that asked yes/no questions for a school project. -Thanks!
12
23319
by: ThaSaltyDawg | last post by:
I have an application that prints to a Thermal Printer..These are the older printers (brand Zebra 3742) and uses the Serial Com Port 1 & 2. I have that working. We now have two new printers (brand Zebra 3842) but are USB. Now I have to write code to print to these USB printers but not sure where to start. Using the system printing functions won't due because I had trouble sending the ELP Commands this way. I am still looking into this method...
0
9512
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10419
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10201
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10147
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9023
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6770
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5424
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5552
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3709
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.