1. Computing & Technology

Python-Powered Port Scanner

From , former About.com Guide

4 of 4

Options and Name Calling

As usual, a function is not worth much until you call it. Here we check whether the program has been imported (i.e., called as part of another program) or whether it has been called independently. To do this, we check the value of __name__.

 if __name__ == '__main__': 
 parser = OptionParser() 
 parser.add_option("-a", "--address", dest="address", default="localhost", help="ADDRESS for server", metavar="ADDRESS") 
 parser.add_option("-p", "--port", dest="port", help="PORT for server", metavar="PORT") 
 (options, args) = parser.parse_args() 
 if options.port == 'all': 
 print 'checking all ports...' 
 for x in range(1,65536): 
 print 'checking port %s on %s' %(x, options.address) 
 check = scan_server(options.address, x) 
 print 'scan_server returned %s' %(check) 
 else: 
 options.port = int(options.port) 
 print 'options: %s, args: %s' %(options, args) 
 check = scan_server(options.address, options.port) 
 print 'scan_server returned %s' %(check) 
 sys.exit(not check) 
After verifying that the program is running on its own, we need to add some options and scan the port. We add several options to the program as part of an object parser of OptionParser, a class of the optparse module.

We then call scan_server to scan the given port. Depending on whether the port instance is 'all' or not, the scan_server function will be called repeatedly with a range of addresses or once. All output goes to the screen, so be prepared for off-the-screen output if you use the 'all' option. If the value for port does not otherwise resolve to an integer through the int() function, Python will throw a ValueError. When all calls are completed, we exit the program using sys.exit().

  1. About.com
  2. Computing & Technology
  3. Python
  4. Networking
  5. Learn Python - Network Programming - Port Scanning - Python-Powered Port Scanner - Options and Name Calling

©2012 About.com. All rights reserved.

A part of The New York Times Company.