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

以上!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM