Search code examples
pythonoptimizationnmap

Any way to optimize/properly refine this <50 line script?


I'm still learning python, and one of the first projects I decided to dive into was something to sort through large nmap logs, pull out the OPEN ports, and dump them to a separate text file in IP:Port format. It works, but is there a better way to write this? Here's what I ended up with:

import sys
import string

"""
Written 6/24/2011 to pull out OPEN ports of an nmap proxy scan
Command:
nmap 218.9-255.0-255.0-255 -p 8080,3128,1080 -M 50 -oG PLog3.txt
"""
if len(sys.argv) != 3:
    print 'Usage: python proxy.py <input file> <output file>'
    print 'nmap 218.1-255.0-255.0-255 -p 8080,3128,1080 -M 50 -oG PLog.txt'
    print 'Example: python ./proxy.py PLog.txt proxies.txt'
    sys.exit(1)

r = open(sys.argv[1], 'r')
o = open(sys.argv[2], 'w')

pat80 = '80/open/'
pat8080 = '8080/open'
pat3128 = '3128/open'

for curline in r.xreadlines():
    sift = string.split(curline, ' ')
    ip = sift[1]

if curline.find(pat3128) >= 0:
    curport = '3128'

elif curline.find(pat8080) >= 0:
    curport = '8080'

elif curline.find(pat80) >= 0:
    curport = '80'

else:
    curport = '100'
    pass


if (curport == '3128') or (curport == '8080') or (curport == '80'):
    o.write(ip + ':' + curport + '\n')
    print ip + ':' + curport

else:
    pass

Solution

  • You can loop over a file like this. There is no need to use xreadlines(). with makes sure the file is closed when r goes out of scope

    with open(sys.argv[1], 'r') as r:
        for curline in r:
            sift = string.split(curline, ' ')
            ip = sift[1]
    
        ...
    

    Looking in a tuple is neater than the chain of or

    if curport in ('3128', '8080', '80'):