python nmap模块扫码端口

操作系统:centos7.4
官网地址: https://pypi.org/project/python-nmap/
漏洞网址: https://www.exploit-db.com/

一、安装

#首先安装nmap包
$ yum -y install nmap

#安装模块
$ pip install python-nmap

备注:
此处安装的是 python-nmap 模块,不是 nmap 模块
如果安装了 nmap 模块,在实例化对象 [“nmap.PortScanner()”] 的时候会报以下错误

AttributeError: 'module' object has no attribute 'PortScanner'

二、用法

>>> import nmap
>>> nm = nmap.PortScanner()    #实例化对象
>>> nm.scan('127.0.0.1', '15-100')  #扫描主机127.0.0.1,端口从15到50

>>> nm.command_line()   #获取用于扫描的命令行
'nmap -oX - -p 15-100 -sV 127.0.0.1'

>>> nm.scaninfo()   #获取nmap扫描信息
{'tcp': {'services': '15-100', 'method': 'connect'}}

>>> nm.all_hosts()   #获得所有被扫描的主机
['127.0.0.1']

>>> nm['127.0.0.1'].hostname()   #为主机127.0.0.1获取一个主机名
'localhost'

>>> nm['127.0.0.1'].hostnames()  #获取主机127.0.0.1的主机名以列表格式输出,里面是一个个字典
[{'type': 'PTR', 'name': 'localhost'}]

>>> nm['127.0.0.1'].state()   #获取主机状态信息 (up|down|unknown|skipped) 
'up'

>>> nm['127.0.0.1'].all_protocols()  #在(ip|tcp|udp|sctp)中获取所有扫描协议['tcp', 'udp']
['tcp']

>>> nm['127.0.0.1']['tcp'].keys()   #获取tcp协议的所有端口
[80, 25, 443, 22, 111]

>>> nm['127.0.0.1'].all_tcp()   #获取tcp协议的所有端口
[21, 22, 25, 83]

>>> nm['127.0.0.1'].all_udp()   #获取udp协议的所有端口
[]

>>> nm['127.0.0.1'].all_ip()   #获取ip协议的所有端口
[]

>>> nm['127.0.0.1'].has_tcp(22)  #主机127.0.0.1上是否有22/tcp端口的信息
True

>>> nm['127.0.0.1'].has_tcp(23)  #主机127.0.0.1上是否有23/tcp端口的信息
False

>>> nm['127.0.0.1']['tcp'][22]   #在主机127.0.0.1上获取tcp端口22的信息
{'state': 'open', 'reason': 'syn-ack', 'name': 'ssh'}

>>> nm['127.0.0.1'].tcp(22)      #在主机127.0.0.1上获取tcp端口22的信息
{'state': 'open', 'reason': 'syn-ack', 'name': 'ssh'}

>>> nm['127.0.0.1']['tcp'][22]['state']    #在主机127.0.0.1上获取端口22/tcp状态
'open'

三、简单扫描端口代码

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:Mr Yang

import nmap
host= '192.168.16.191'
nm = nmap.PortScanner()
for port in range(20,25):
    result = nm.scan(host,str(port))
    state = result['scan']['192.168.16.191']['tcp'][int(port)]['state']
    print('[%s] port state: %s' %(port,state))

四、升级版本

#!/usr/bin/env python
#-*- coding:utf-8 -*-
# author:Mr Yang

import nmap
import optparse
import sys
class INFO(object):
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    ARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

def scanport(host, port):
    nm = nmap.PortScanner()
    try:
        result = nm.scan(host,port)
        state = result['scan'][host]['tcp'][int(port)]['state']  # 多层字典嵌套取值
        if state == 'open':
            print(INFO.OKBLUE+'[*] '+host+ ' tcp/'+port+" "+state+INFO.ENDC)
        else:
            print(INFO.WARNING+'[*] '+host+ ' tcp/'+port+" "+state+INFO.ENDC)
    except Exception as e:
        pass

if __name__ == '__main__':
    parser = optparse.OptionParser("usage args: -H host -p port1,port2,... or -p start_port - end_port ")
    parser.add_option('-H', dest='Host', type='string', help='specify target host')
    parser.add_option('-P', dest='Port', type='string', help='specify target port[s] separated by "-"'or ",")
    options, args = parser.parse_args()
    if options.Host ==None or options.Port==None:
        print(parser.usage)
        sys.exit()
    host = options.Host
    ports = options.Port
    print(host,ports)

    #如果是连续的端口
    if '-' in ports:
        ports_list = ports.split('-')
        for p in range(int(ports_list[0]),int(ports_list[1])+1):
            scanport(host, str(p))
    #非连续端口
    else:
        ports_list = ports.split(',')
        for p in ports_list:
            scanport(host, p)

运行

#格式 python 脚本名称 -H 主机名 -P 端口 
$ python test.py -H 192.168.16.191 -P 15-50

#也可以用逗号分隔指定端口,这样是非连续端口
$ python test.py -H 192.168.16.191 -P 22,3306,80,8000  #扫描 22,3306,80,8000 端口

扫描 主机:192.168.16.191 的 15至50端口
python nmap模块扫码端口_第1张图片

你可能感兴趣的:(python)