1. 程式人生 > >python-nmap使用方法(python3)

python-nmap使用方法(python3)

python nmap python-nmap

nmap是一個知名的端口掃描工具,超級好用,可調的參數也多(但需懂得網絡相關知識,否則就別費精神研究參數了)

一般在linux上使用,當然,它也有windows的版本,但不在這裏展開。


關於nmap的用法,可以參考在線手冊 https://nmap.org/book/man-briefoptions.html

python-nmap 實際是在python裏面調用底層的nmap,所以第一步是先安裝系統的nmap,再裝python-nmap


以下是安裝步驟

本文使用的系統是centos 6,python的版本是3.5.2


1)安裝系統的nmap

# yum install nmap -y

......

Package 2:nmap-5.51-6.el6.x86_64 already installed and latest version

Nothing to do

由於我已經裝過了,所以提示已安裝

驗證一下

# nmap -v

Starting Nmap 5.51...


2)安裝python-nmap

[root@Lab2 ~]# pip3 install python-nmap

Requirement already satisfied: python-nmap in ....

同樣已經裝過


以下是python3中使用(https://xael.org/pages/python-nmap-en.html

最基本的用法,也是串行的方式,請自行去上面的網站上查詢

這裏說的是異步方式,要使用python來進行掃描,我相信大多是批量掃描,否則沒必要用python,直接在命令行下執行nmap

python-nmap有兩種異步的使用方式,根據源碼來看,實際上就是多進程。


第一種:

# 先定義一個回調方法,參數必須是兩個,名字隨便取,這裏用的是host和scan_result

import nmap
def callback_result(host, scan_result):
    print('------------------')
    print(host, scan_result)
    
# 異步Scanner
nm = nmap.PortScannerAsync()

# 掃描參數,第一個是掃描對象,可以是單個IP、網段、IP-IP諸多寫法,詳細自己查手冊或者百度
# 第二個是ports參數,同樣寫法多樣
# 第三個arguments參數,這個就有講究了,假如不寫這個參數,默認會帶一個-sV,然後你掃描一個ip都能等到天荒地老,關於-sV的含義在文後給出作為參考。在這裏,我們給一個-sS,或者可以給個空白字符串也是可以的
# 第四個是指定回調函數
nm.scan('192.168.1.0/24', ports='22,80,8888', arguments='-sS', callback=callback_result)

# 以下是必須寫的,否則你會看到一運行就退出,沒有任何的結果
while nm.still_scanning():
    print("sleep")
    nm.wait(2)



第二種:

import nmap
nm = nmap.PortScannerYield()
for result in nm.scan('192.168.1.0/24', ports='22,80,8888,8080,443', arguments="-sS"):
    print(result)

這種調用方式簡單很多,也是推薦的寫法。得到的結果

 ('192.168.1.1', {'scan': {'192.168.1.1': {'tcp': {80: {'extrainfo': '', 'state': 'filtered', 'name': 'http', 'product': '', 'reason': 'no-response', 'conf': '3', 'cpe': '', 'version': ''}, 8080: {'extrainfo': '', 'state': 'filtered', 'name': 'http-proxy', 'product': '', 'reason': 'no-response', 'conf': '3', 'cpe': '', 'version': ''}, 443: {'extrainfo': '', 'state': 'closed', 'name': 'https', 'product': '', 'reason': 'reset', 'conf': '3', 'cpe': '', 'version': ''}, 22: {'extrainfo': '', 'state': 'closed', 'name': 'ssh', 'product': '', 'reason': 'reset', 'conf': '3', 'cpe': '', 'version': ''}, 8888: {'extrainfo': '', 'state': 'open', 'name': 'sun-answerbook', 'product': '', 'reason': 'syn-ack', 'conf': '3', 'cpe': '', 'version': ''}}, 'vendor': {}, 'status': {'state': 'up', 'reason': 'timestamp-reply'}, 'addresses': {'ipv4': '192.168.1.1'}, 'hostnames': [{'type': '', 'name': ''}]}}, 'nmap': {'scanstats': {'uphosts': '1', 'downhosts': '0', 'elapsed': '1.29', 'totalhosts': '1', 'timestr': 'Wed Jun 13 17:25:28 2018'}, 'command_line': 'nmap -oX - -p 22,80,8888,8080,443 -sS 192.168.1.1', 'scaninfo': {'tcp': {'services': '22,80,443,8080,8888', 'method': 'syn'}}}})


如何分析使用result,各位自己發揮吧, 它其實就是個元組,內嵌了字典


SERVICE/VERSION DETECTION:

-sV: Probe open ports to determine service/version info # 探測端口的服務、版本信息


python-nmap使用方法(python3)