leonteale

NmapParser.py

Sep 8th, 2015
162
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.11 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. import csv
  4. import sys
  5.  
  6. # Name of file
  7. finput = sys.argv[1]
  8. fout_suffix = "_nmap.csv"
  9. cols = ['PORT', 'STATE', 'SERVICE', 'VERSION']
  10.  
  11. def getIP(line):
  12.     if not line:    return None
  13.     if 'Nmap scan report for' in line:
  14.         return line[21:-1]
  15.     return ''
  16.  
  17. def findHead(line):
  18.     if not line:  return False
  19.     for i in cols:
  20.         if i not in line:
  21.             return False
  22.     return True
  23.  
  24. def parseData(line):
  25.     data = []
  26.     for i in line.split():
  27.         if i.isspace(): continue
  28.         if len(data) == 0:
  29.             for j in i.strip().split('/'):
  30.                 data.append(j)
  31.         else:
  32.             data.append(i.strip())
  33.        
  34.     # Get the version type
  35.     i = 4
  36.     version = ''
  37.     while i < len(data):
  38.         version += ' ' + data[i]
  39.         data.remove(data[i])
  40.     if version:
  41.         data.append(version.strip())
  42.  
  43.     return data
  44.  
  45. def checkLine(line):
  46.     for i in line:
  47.         if i.isdigit(): continue
  48.         if i == '/':    return True
  49.         return False
  50.  
  51. # Open the file
  52. with open(finput, 'r') as fin:
  53.     while True:
  54.         # Get IP address
  55.         while True:
  56.             ip = getIP(fin.readline())
  57.             if ip != '':    break
  58.         if ip == None:
  59.             break
  60.        
  61.         # Get first column from port scan
  62.         while not findHead(fin.readline()):
  63.             pass
  64.            
  65.         # Get all data
  66.         data = []
  67.         while True:
  68.             line = fin.readline()
  69.             # All lines stating with '|' will be ignored
  70.             if line[0] == '|':  continue
  71.            
  72.             # Check if line is invalid
  73.             if not checkLine(line):   break
  74.            
  75.             # Record the line
  76.             data.append(parseData(line))
  77.  
  78.         # Output into file
  79.         with open(ip + fout_suffix, 'wb') as csvfile:
  80.             # Get file to be written
  81.             rows = csv.writer(csvfile)
  82.             cols.insert(1, 'PROTOCOL')
  83.             rows.writerow(cols)
  84.             cols.remove('PROTOCOL')
  85.             # Print all the rows
  86.             rows.writerows(data)
Advertisement
Add Comment
Please, Sign In to add comment