0

So I found nmap and print(nm.csv()) help needed to print out to csv.file that gave me the code I am working with now. The last few lines of code where the def is.

But the csv file that is generated has all the data in one column. Is there a way to force it to put each data set in its own column? Or should I stick with using Excel to separate after the fact?

The data I am "printing" is formatted like this; and I believe is a key pair. 'host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe' ...

import sys
import os
import nmap
from datetime import datetime
import time
import csv


#Ask for user input and assign IP\subnet and port range.
print("_" * 40) #style options
ip_range = '192.168.3.132' #str(input('\nEnter an IP or subnet: '))
user_ports = '100-200' #str(input('\nEnter Ports to scan: '))
print("\nScanning IP " + ip_range + ". For ports " + user_ports + ".")



#add banner containing time stamps.
before = datetime.now()
print("_" * 40) #style options
print("\nScanning Target "+ip_range)
print('\n') #style options
print("Time Started: "+ str(datetime.now().strftime('%m-%d-%Y %H:%M:%S'))+'\n')



print("~" * 40)#style options
print('\n')#style options


#name scan configuration
nmap_scan = nmap.PortScanner()
nmap_scan.scan(str(ip_range), str(user_ports))

#printing out ports that are up
for host in nmap_scan.all_hosts():
    print("Host: %s (%s)" % (host, nmap_scan[host].hostname()))
    print("state: %s" % nmap_scan[host].state())
    for proto in nmap_scan[host].all_protocols():
        print("\n")
        print("Protocol used: %s" % proto)

        lport = sorted(nmap_scan[host][proto].keys())
        for port in lport:
            print("Port: %s\tState: %s" % (port, nmap_scan[host][proto][port]['state']))


print('\n')#style options

#export nmap scan to csv file
#export nmap scan to csv file
def save_csv_data(nmap_scan_csv, path='.'):
        with open(path + '/output.csv', 'w') as output:
            output.write(nmap_scan_csv)

if (len(sys.argv) > 1 and sys.argv[1]):
    save_csv_data(nmap_scan.csv(), path=sys.argv[1])
else:
    save_csv_data(nmap_scan.csv())

print("_" * 50)#style options
print('\n\n')#style options

#Finished time
after = datetime.now()
print("Time finished: "+ str(datetime.now().strftime('%m-%d-%Y %H:%M:%S')))

#time elapsed during scan
print('\n')#style options
delta =  after-before
print("Time elapsed: " + str(delta))

'''

  • Please include a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – LeoE Jan 17 '20 at 16:26
  • your data looks like it is separated with `;` make sure to use this as your csv separator instead of the default of `,` – Dan Jan 17 '20 at 16:27
  • I have been trying tons of things to figure out how to specific the delimiter to be ';'. Any suggestions? – AverageInfosec Jan 17 '20 at 19:17
  • What does `nm.csv()` look like? Do you have a [mcve]? – AMC Jan 17 '20 at 19:25
  • `192.168.1.5;computer.contoso.com;PTR;tcp;135;msrpc;open;Microsoft Windows RPC;;syn-ack;;10;cpe:/o:microsoft:windows` this is what the excel current outputs into 1 cell. it also outputs headers `host;hostname;hostname_type;protocol;port;name;state;product;extrainfo;reason;version;conf;cpe `. I can post the whole code but youll need to install nmap should I post it all? – AverageInfosec Jan 17 '20 at 19:40
  • What excel? In any case, if you want to change the delimiter safely, you can use the csv module. Otherwise, a simple `.replace()` should do. – AMC Jan 17 '20 at 19:50
  • _I can post the whole code but youll need to install nmap should I post it all?_ Just some example output of `nm.csv()` should be alright, and it might not even be necessary at all. – AMC Jan 17 '20 at 19:52
  • I have updated my post with the full code. – AverageInfosec Jan 17 '20 at 20:08
  • Alright, have you tried the `.replace()` or csv module idea? – AMC Jan 17 '20 at 20:08
  • Actually, if all you need is to get this to work in Excel, take a look at this: https://superuser.com/q/180964. – AMC Jan 17 '20 at 20:12
  • I think the .replace() may work, but I am not sure where to put it. Im very new to python :( I can modify the resulting output csv to text to columns, but would love to get it all done before I even open the csv – AverageInfosec Jan 17 '20 at 20:17
  • I GOT IT. yay. It was `output.write(nmap_scan_csv.replace(';', ','))` that i had to change. Thank you AMC! You got me on the right track. Idk how to mark you as correct answer? Maybe if you post a whole new comment I can mark it. – AverageInfosec Jan 17 '20 at 20:23
  • @AverageInfosec I can always post an answer, I guess. Be careful though, using `.replace()` can be dangerous. If this is only for Excel, the solution I linked above should be fine. – AMC Jan 17 '20 at 20:28
  • @AverageInfosec I had this in my saved posts, and I can't even remember what I did to help... – AMC Jan 23 '20 at 01:20
  • @AMC you told me to add `.replace` to `output.write(nmap_scan_csv.replace(';', ','))` which is what was missing. – AverageInfosec Jan 23 '20 at 12:59
  • @AverageInfosec Wait, that worked? – AMC Jan 23 '20 at 18:30
  • @amc Yep, I ended up doing something totally different as I continued further, but that gave me a csv properly formatted the way i needed when i asked. – AverageInfosec Jan 23 '20 at 20:24

0 Answers0