标签:python-nmap 端口扫描
python-nmap是对nmap命令的封装,方便python操作nmap扫描器首先安装nmap
yum install nmap -y
##shell命令操作端口扫描方法见此文:http://blog.51cto.com/superleedo/2094273
接着安装python-nmap模块
打开 https://pypi.org/project/python-nmap/#files
cd python-nmap-0.6.1
python setup.py install
扫描应用示例
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import nmap scan_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: #调用扫描方法,参数指定扫描主机hosts,nmap扫描命令行参数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()) #输出主机状态,如up、down for proto in nm[host].all_protocols(): #遍历扫描协议,如tcp、udp print('----------') print('Protocol : %s' % proto) #输入协议名 lport = nm[host][proto].keys() #获取协议的所有扫描端口 lport.sort() #端口列表排序 for port in lport: #遍历端口及输出端口与状态 print('port : %s\tstate : %s' % (port, nm[host][proto][port]['state']))
执行扫描
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 : tcp port : 22 state : open port : 80 state : open port : 443 state : closed port : 3306 state : open port : 8080 state : open
Please input hosts and port:
上面主机输入支持多种形式 如: www.baidu.com , 192.168.1.* , 192.168.1.1-20, 192.168.1.0/24 其后的端口可以是21,22,80,3306 也可以用21-3306
标签:python-nmap 端口扫描
原文地址:http://blog.51cto.com/superleedo/2118750