Install well Python-Namp modular ,(pip install python-nmap). Create a PortScanner() Class object , This enables us to use this object to complete the scan operation .PortScanner Class has one. scan() function , It can enter a list of targets and ports as parameters , And make a basic Nmap scanning . in addition , You can also put the address of the target host / Put the port into the array for future reference , And print out the status of the port . The sample code is as follows :
# The import module
import nmap
import optparse
# Definition nmapScan function , The parameters are target host and target port
def nmapScan(tgtHost, tgtPort):
# Instantiation nmap Port scan object
nmScan = nmap.PortScanner()
# perform scan() function
nmScan.scan(tgtHost, tgtPort)
# obtain tcp Port status corresponding to the protocol
state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
print(f"[+] {
tgtHost} tcp/{
tgtPort} {
state}")
# Define the main function
def main():
# Instantiate syntax objects
parser = optparse.OptionParser('Usage %prog -H <target host> -p <target port>')
# add to —H, -p Parameter options , Define variable names and types , And help notes
parser.add_option('-H', dest = 'tgtHost', type = 'string', help = 'specify target host')
parser.add_option('-p', dest = 'tgtPort', type = 'string', help = 'specify target port')
# Generate syntax parameter tuples
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(', ')
if tgtHost == None or tgtPorts[0] == None:
print(parser.usage)
exit(0)
for tgtPort in tgtPorts:
nmapScan(tgtHost, tgtPort)
if __name__ == '__main__':
main()
Execute this script , The operation results are as follows :