#!/usr/bin/env python3
import optparse
import nmap
import csv

class NmapScannerCSV:
    def __init__(self):
        self.portScanner = nmap.PortScanner()

    def nmapScanCSV(self, host, ports):
        try:
            print("Skanowanie portów " + str(ports) + " ..........")
            self.portScanner.scan(host, arguments = '-n -p' + ports)
            print("[*] Wykonywane polecenie: %s" % self.portScanner.command_line())
            print(self.portScanner.csv())
            print("Podsumowanie hosta", host)
            with open('csv_file.csv', mode = 'w') as csv_file:
                csv_writer = csv.writer(csv_file, delimiter = ',')
                csv_writer.writerow(['Host', 'Protokół', 'Port', 'Stan'])
                for x in self.portScanner.csv().split("\n")[1:-1]:
                    splited_line = x.split(";")
                    host = splited_line[0]
                    protocol = splited_line[5]
                    port = splited_line[4]
                    state = splited_line[6]
                    print("Protokół: " + protocol + ", port: " + port + ", stan: " + state)
                    csv_writer.writerow([host, protocol, port, state])
        except Exception as exception:
            print("Błąd połączenia z hostem " + host, exception)

def main():
    parser = optparse.OptionParser("%prog " + "--host <adres hosta> --ports <lista portów>") 
    parser.add_option('--host', dest = 'host', type = 'string', help = 'Adres skanowanego hosta.')
    parser.add_option('--ports', dest = 'ports', type = 'string', help = 'Lista portów oddzielonych przecinkami.')
    (options, args) = parser.parse_args()
    if (options.host == None) | (options.ports == None): 
        print('[-] Podaj adres IP hosta i listę portów.')
        exit(0)
    host = options.host
    ports = options.ports
    NmapScannerCSV().nmapScanCSV(host, ports)

if __name__ == "__main__": 
    main()