欢迎来到starnight_cyber的博客

python-nmap 使用基础

前言

  python-nmap是一个Python库,可帮助您使用nmap端口扫描程序。它可以轻松操纵nmap扫描结果,将是一个完美的选择想要自动执行扫描任务的系统管理员的工具和报告。 它还支持nmap脚本输出。

  目前最新版本是0.6.1,具体请参考官方站点

安装

  推荐采用pip安装的方式。

pip install python-nmap
# for 国内,安装0.6.1版本
pip3 install -i https://pypi.douban.com/simple/ python-nmap==0.6.1

使用

基础使用

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

import nmap


def test():
    ip = '172.16.176.120'
    nm = nmap.PortScanner()
    nm.scan(ip, '80, 445', '-v -n -sS -T4 -Pn')
    print(nm.command_line())
    print(nm.scaninfo())
    print(nm.all_hosts())
    print(nm[ip])


if __name__ == '__main__':
    test()
# python3 scan_nmap.py
nmap -oX - -p "80, 445" -v -n -sS -T4 -Pn 172.16.176.120
{'tcp': {'method': 'syn', 'services': '80,445'}}
['172.16.176.120']
{'hostnames': [{'name': '', 'type': ''}], 'addresses': {'ipv4': '172.16.176.120'}, 'vendor': {}, 'status': {'state': 'up', 'reason': 'user-se
t'}, 'tcp': {80: {'state': 'open', 'reason': 'syn-ack', 'name': 'http', 'product': '', 'version': '', 'extrainfo': '', 'conf': '3', 'cpe': ''
}, 445: {'state': 'closed', 'reason': 'reset', 'name': 'microsoft-ds', 'product': '', 'version': '', 'extrainfo': '', 'conf': '3', 'cpe': ''}
}}

主机解析

  扫描之后,通过nm[ip]获取特定ip地址的扫描结果,返回的是一个‘类json格式’,剩下的便是对返回的结果进行解析了。

{
    'hostnames': [{
        'name': '',
        'type': ''
    }],
    'addresses': {
        'ipv4': '172.16.176.120'
    },
    'vendor': {},
    'status': {
        'state': 'up',
        'reason': 'user-set '
    },
    'tcp ': {
        80: {'state ': 'open ',
            'reason ': 'syn - ack ',
            'name ': 'http ',
            'product ': '',
            'version ': '',
            'extrainfo ': '',
            'conf ': '3 ',
            'cpe ': ''
        },
        445: {
            'state': 'closed',
            'reason': 'reset',
            'name': 'microsoft-ds',
            'product': '',
            'version': '',
            'extrainfo': '',
            'conf': '3',
            'cpe': ''
        }
    }
}

  请查看官方示例https://pypi.org/project/python-nmap/

  为了便捷,这里用了ip这个变量,方便更改。

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

import nmap
import json


def test():
    ip = '172.16.176.120'
    nm = nmap.PortScanner()
    nm.scan(ip, '80, 445', '-v -n -sS -T4 -Pn')
    # print(nm.command_line())
    # print(nm.scaninfo())
    # print(nm.all_hosts())
    # print(nm[ip])
    print('主机名 => ', nm[ip].hostname())
    print('主机状态 => ', nm[ip].state())
    print('所有协议 => ', nm[ip].all_protocols())
    print('TCP协议的所有端口 => ', nm[ip]['tcp'].keys())
    print('获取tcp协议的所有端口(已排序) => ', nm[ip].all_tcp())
    print('获取udp协议的所有端口(已排序) => ', nm[ip].all_udp())
    print('是否存在某个tcp端口 => ', nm[ip].has_tcp(80))
    print('获取有关TCP中端口80的信息 => ', nm[ip].tcp(80))
    print('获取有关TCP中端口80的信息(json展开) => ')
    print(json.dumps(nm[ip]['tcp'][80], indent=4, separators=(',', ':')))
    print('获取端口80 / tcp的状态 =>', nm[ip]['tcp'][80]['state'])


if __name__ == '__main__':
    test()

  结果如下:

python3 scan_nmap.py
主机名 =>
主机状态 =>  up
所有协议 =>  ['tcp']
TCP协议的所有端口 =>  dict_keys([80, 445])
获取tcp协议的所有端口(已排序) =>  [80, 445]
获取udp协议的所有端口(已排序) =>  []
是否存在某个tcp端口 =>  True
获取有关TCP中端口80的信息 =>  {'state': 'open', 'reason': 'syn-ack', 'name': 'http', 'product': '', 'version': '', 'extrainfo': '', 'conf': '
3', 'cpe': ''}
获取有关TCP中端口80的信息(json展开) =>
{
    "state":"open",
    "reason":"syn-ack",
    "name":"http",
    "product":"",
    "version":"",
    "extrainfo":"",
    "conf":"3",
    "cpe":""
}
获取端口80 / tcp的状态 => open

  获取到某个ip的扫描结果,即可对nm[ip]的结果解析即可。

python-nmap

scan函数

def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', sudo=False):
        """
        Scan given hosts

        May raise PortScannerError exception if nmap output was not xml

        Test existance of the following key to know
        if something went wrong : ['nmap']['scaninfo']['error']
        If not present, everything was ok.

        :param hosts: string for hosts as nmap use it 'scanme.nmap.org' or '198.116.0-255.1-127' or '216.163.128.20/20'
        :param ports: string for ports as nmap use it '22,53,110,143-4564'
        :param arguments: string of arguments for nmap '-sU -sX -sC'
        :param sudo: launch nmap with sudo if True

        :returns: scan_result as dictionnary
        """

  scan函数定义如上,使用python-nmap传入参数格式跟使用nmap是一致的,填入arguments即可。

其它函数

  感觉没有更多特别的东西,简单列出,具体可以参考源代码。

C:\Users\Administrator\Downloads\python-nmap-0.6.1\python-nmap-0.6.1\nmap\nmap.py (50 hits)
    Line 82:     def __init__(self, nmap_search_path=('nmap', '/usr/bin/nmap', '/usr/local/bin/nmap', '/sw/bin/nmap', '/opt/local/bin/nmap')):
    Line 159:     def get_nmap_last_output(self):
    Line 168:     def nmap_version(self):
    Line 176:     def listscan(self, hosts='127.0.0.1'):
    Line 191:     def scan(self, hosts='127.0.0.1', ports=None, arguments='-sV', sudo=False):
    Line 270:     def analyse_nmap_xml_scan(self, nmap_xml_output=None, nmap_err='', nmap_err_keep_trace='', nmap_warn_keep_trace=''):
    Line 560:     def __getitem__(self, host):
    Line 571:     def all_hosts(self):
    Line 582:     def command_line(self):
    Line 594:     def scaninfo(self):
    Line 607:     def scanstats(self):
    Line 620:     def has_host(self, host):
    Line 633:     def csv(self):

参考

  官方文档:https://pypi.org/project/python-nmap/

  Python-nmap 使用文档:https://www.twblogs.net/a/5c836630bd9eee35cd69b516/zh-cn

以上!

posted @ 2020-04-13 16:57  starnight_cyber  阅读(2637)  评论(0编辑  收藏  举报