Wednesday, March 3, 2010

March Madness Challenge - MMC03

I wrote a little program that checks if a web server is running at a user specified ip address. While I was browsing to the documentation is saw OptionParse. This is a really nice way to parse arguments. Especially the -h option, that will generate the usage info automatically.

Possible output:

python mmc03.py -i 127.0.0.1 -r /
***** MMC03 *****
Port 80 check successfull!
Webserver is running! Response: 302 Found

python mmc03.py -i 127.0.0.1 -r /
***** MMC03 *****
Port 80 check failed: [Errno 10061] No connection could be made because the target machine actively refused it


1 #! /usr/bin python
2
3 import httplib
4
5 def checkPort(ip, resource):
6 if not resource.startswith('/'):
7 resource = '/' + resource
8
9 try:
10 conn = httplib.HTTPConnection(ip, httplib.HTTP_PORT)
11 conn.request('GET', resource)
12 response = conn.getresponse()
13 print 'Port %s check successfull!' % httplib.HTTP_PORT
14 if (httplib.responses[response.status]):
15 print 'Webserver is running! Response: %s %s' % \
16 (response.status, response.reason)
17 except Exception, e:
18 print 'Port %s check failed: %s' % (httplib.HTTP_PORT, e)
19 return False
20 finally:
21 conn.close()
22
23 if __name__ == '__main__':
24 print '***** MMC03 *****'
25
26 from optparse import OptionParser
27 parser = OptionParser()
28 parser.add_option("-i", "--ip", dest="ip", default='127.0.0.1',
29 help='ip address of server')
30 parser.add_option("-r", "--resource", dest="resource", default="/",
31 help="resource to check")
32 (options, args) = parser.parse_args()
33
34 checkPort(options.ip, options.resource)
35

No comments:

Post a Comment