First edition: Only comma-separated ports are supported and port ranges are not supported
Firstly:sudo Apt-get Install Nmap
Secondly:pip Install Python-nmap
Thirdly:copy the code bellow to a file like scan_network.py
#!/usr/bin/env pythonimport nmapimport optparsedef nmapScan (TgtHost, Tgtport): Nmscan = Nmap. Portscanner () Nmscan.scan (tgthost,tgtport) state=nmscan[tgthost][' TCP '][int (tgtport) [' State '] print ("[*]" + TG Thost + "tcp/" +tgtport + "" +state) def Main (): parser = Optparse. Optionparser (' Usage%prog ' +\ '-H <target host>-P <target port> ') parser . Add_option ('-h ', dest= ' tgthost ', type= ' string ', \ help= ' Specify target host ') Parser.add_option ('- P ', dest= ' tgtport ', type= ' string ', \ help= ' specify target port[s] separated by comma ') (options , args) = Parser.parse_args () tgthost = options.tgthost tgtports = str (options.tgtport). Split (', ') if (TG Thost = = None) | (Tgtports[0] = None): print (parser.usage) exit (0) for Tgtport in Tgtports:nmapscan (Tgthost, TGT Port) If name = = ' main ': main
Forthly:chmod +x scan_network.py
Fifthly:./scan_network.py-h 192.168.1.1-p 22,23
Second Edition: Supports comma-separated and-split port ranges
#!/usr/bin/env pythonimport nmapimport optparsedef nmapscan (tgthost,tgtport): Nmscan = Nmap. Portscanner () Nmscan.scan (tgthost,tgtport) state=nmscan[tgthost][' TCP '][int (tgtport) [' State '] print ("[*]" + TG Thost + "tcp/" +tgtport + "" +state) def Main (): parser = Optparse. Optionparser (' Usage%prog ' +\ '-H <target host>-P <target port> ') parser . Add_option ('-h ', dest= ' tgthost ', type= ' string ', \ help= ' Specify target host ') Parser.add_option ('- P ', dest= ' tgtport ', type= ' string ', \ help= ' specify target port[s] separated by comma ') (Options, AR GS) = Parser.parse_args () tgthost = options.tgthost##### #this code bellow is-to-support scan port range like 66-88 t Gtports = [] Tgtports_cache = str (options.tgtport). Split (', ') i = Int (len (tgtports_cache)) for M in Range (0,i): Tgtports_split = str (tgtports_cache[m]). Split ('-') if (Len (Tgtports_split) < 2): Tgtports.extend (Tgtports_split) #print (tgtports) else:for n in range (int (tgtports_split[ 0]), int (tgtports_split[1]) +1): Tgtports.append (str (n)) #print (tgtports) ##### #above the TGTPO RTS is the ports list want to Scann #tgtPorts = str (options.tgtport). Split (', ') if (tgthost = None) | (Tgtports[0] = None): print (parser.usage) exit (0) for Tgtport in Tgtports:nmapscan (Tgthost, TGT Port) If name = = ' Main ': Main ()