Python-nmap is an encapsulation of NMAP commands, allowing Python to operate the Nmap scanner
First install Nmap
Yum Install Nmap-y
# #shell命令操作端口扫描方法见此文: http://blog.51cto.com/superleedo/2094273
Then install the Python-nmap module
Open https://pypi.org/project/python-nmap/#files
wget https://files.pythonhosted.org/packages/dc/f2/9e1a2953d4d824e183ac033e3d223055e40e695fa6db2cb3e94a864eaa84 /python-nmap-0.6.1.tar.gz
CD python-nmap-0.6.1
Python setup.py Install
Scanning Application Examples
#!/usr/bin/env python# -*- coding: utf-8 -*-import sysimport nmapscan_row=[ ] input_data = raw_input ("please input hosts and port: ") Scan_row = input_data.split (" ") if len (scan_row)!=2: print " Input errors,example \ "192.168.1.0/24 80,443,22\" " sys.exit (0) hosts=scan_row[0] #接收用户输入的主机port =scan_row[1] #接收用户输入的端口try: nm = nmap. Portscanner () #创建端口扫描对象except nmap. Portscannererror: print (' Nmap not found ', sys.exc_info () [0]) sys.exit (0) Except: print ("Unexpected error:", sys.exc_info () [0]) sys.exit (0) try: #调用扫描方法, parameters specify the scan host Hosts,nmaP Scan command line parameter Arguments nm.scan (hosts=hosts, arguments= ' -v -sS -p ' +port) except exception as e: print "Scan erro:" +str (e) For host in nm.all_hosts (): #遍历扫描主机 print ('------------------------ ----------------------------') print (' host : %s (%s) ' % (Host, nm[host].hostname ()) #输出主机及主机名 print (' state : %s ' % nm[ Host].state ()) #输出主机状态, e.g. up, Down for proto in nm[host].all_ Protocols (): #遍历扫描协议, such as TCP, Udp print ('----------') print (' protocol : %s ' % proto) #输入协议名 lport = nm[host][proto].keys () #获取协议的所有扫描端口 &nbsP; lport.sort () #端口列表排序 for port in lport: #遍历端口及输出端口与状态 print (' port : %s\tstate : %s ' % (port, nm[host][proto][port][' state ') ))
Perform a scan
Python scan.py Please input hosts and port:192.168.1.124 80,443,22,3306,8080----------------------------------------- -----------host:192.168.1.124 (test01.test.com.cn) state:up----------protocol:tcpport:22 State:openport:8 0 state:openport:443 state:closedport:3306 state:openport:8080 state:open
Please input hosts and port:
The above host input supports a variety of forms such as: www.baidu.com, 192.168.1.*, 192.168.1.1-20, 192.168.1.0/24 after the port can be 21,22,80,3306 can also be used 21-3306
Python-nmap Port Scan Example