Python之NMAP詳解

1、NMAP簡介

NMap,也就是Network Mapper,最先是Linux下的網絡掃描和嗅探工具包。html

nmap是一個網絡鏈接端掃描軟件,用來掃描網上電腦開放的網絡鏈接端。肯定哪些服務運行在哪些鏈接端,而且推斷計算機運行哪一個操做系統(這是亦稱 fingerprinting)。它是網絡管理員必用的軟件之一,以及用以評估網絡系統安全。python

正如大多數被用於網絡安全的工具,nmap 也是很多黑客及駭客(又稱腳本小子)愛用的工具 。系統管理員能夠利用nmap來探測工做環境中未經批准使用的服務器,可是黑客會利用nmap來蒐集目標電腦的網絡設定,從而計劃攻擊的方法。linux

Nmap 常被跟評估系統漏洞軟件Nessus 混爲一談。Nmap 以隱祕的手法,避開闖入檢測系統的監視,並儘量不影響目標系統的平常操做。shell

Nmap 在黑客帝國(The Matrix)中,連同SSH1的32位元循環冗餘校驗漏洞,被崔妮蒂用以入侵發電站的能源管理系統。安全

2、功能介紹

基本功能有三個,一是探測一組主機是否在線;其次是掃描 主機端口,嗅探所提供的網絡服務;還能夠推斷主機所用的操做系統 。Nmap可用於掃描僅有兩個節點的LAN,直至500個節點以上的網絡。Nmap 還容許用戶定製掃描技巧。一般,一個簡單的使用ICMP協議的ping操做能夠知足通常需求;也能夠深刻探測UDP或者TCP端口,直至主機所 使用的操做系統;還能夠將全部探測結果記錄到各類格式的日誌中, 供進一步分析操做。服務器

進行ping掃描,打印出對掃描作出響應的主機,不作進一步測試(如端口掃描或者操做系統探測):網絡

nmap -sP 192.168.1.0/24
僅列出指定網絡上的每臺主機,不發送任何報文到目標主機:

nmap -sL 192.168.1.0/24
探測目標主機開放的端口,能夠指定一個以逗號分隔的端口列表(如-PS22,23,25,80):

nmap -PS 192.168.1.234
使用UDP ping探測主機:

nmap -PU 192.168.1.0/24
使用頻率最高的掃描選項:SYN掃描,又稱爲半開放掃描,它不打開一個徹底的TCP鏈接,執行得很快:

nmap -sS 192.168.1.0/24

3、NMAP安裝

本文以linux Ubuntu16.04爲例,最後主要用python操做

1. 先安裝nmap

sudo apt-get install nmap
2.再安裝python-nmap

sudo pip3.6 install python-nmap
安裝完以後python導入nmap測試驗證是否成功

➜  ~ python3.6
Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>>
>>>
>>> import nmap

4、Python操做NMAP

案例

建立PortScanner實例,而後掃描159.239.210.26這個IP的20-443端口。多線程

import nmap

nm = nmap.PortScanner()
ret = nm.scan('115.239.210.26','20')
print (ret)

返回格式以下:
{'nmap': {'scanstats': 
{'uphosts': '1', 'timestr': 'Tue Oct 25 11:30:47 2016', 'downhosts': '0', 'totalhosts': '1', 'elapsed': '1.11'},
 'scaninfo': {'tcp': {'services': '20', 'method': 'connect'}}, 'command_line': 'nmap -oX - -p 20 -sV 115.239.210.26'},
 'scan': {'115.239.210.26': {'status': {'state': 'up', 'reason': 'syn-ack'}, 'hostnames': [{'type': '', 'name': ''}],
 'vendor': {}, 'addresses': {'ipv4': '115.239.210.26'},
 'tcp': {20: {'product': '', 'state': 'filtered', 'version': '', 'name': 'ftp-data', 'conf': '3', 'extrainfo': '', 
'reason': 'no-response', 'cpe': ''}
}
}
}
}

內置方法

import nmap  
nm = nmap.PortScanner() 
print (nm.scaninfo())
# {u'tcp': {'services': u'20-443', 'method': u'syn'}}
print (nm.command_line())
# u'nmap -oX - -p 20-443 -sV 115.239.210.26' 


# 查看有多少個host

print (nm.all_hosts())
# [u'115.239.210.26'] 
# 查看該host的詳細信息

nm['115.239.210.26']
# 查看該host包含的全部協議

nm['115.239.210.26'].all_protocols() 
# 查看該host的哪些端口提供了tcp協議

nm['115.239.210.26']['tcp']

nm['115.239.210.26']['tcp'].keys() 
# 查看該端口是否提供了tcp協議

nm['115.239.210.26'].has_tcp(21)
# 還能夠像這樣設置nmap執行的參數

nm.scan(hosts='192.168.1.0/24', arguments='-n -sP -PE -PA21,23,80,3389')

5、檢測內網機器端口

定義函數庫mytools.pyapp

#-*- coding:utf-8 -*- 
import smtplib 
from email.mime.text import MIMEText 
from email.header import Header 
def sendemail(sender,receiver,subject,content,smtpserver,smtpuser,smtppass): 
    msg = MIMEText(content,'html','utf-8')#中文需參數‘utf-8',單字節字符不須要 
    msg['Subject'] = Header(subject, 'utf-8') 
    msg['From'] = '<%s>' % sender 
    msg['To'] = ";".join(receiver) 
    try: 
        smtp = smtplib.SMTP() 
        smtp.connect(smtpserver) 
        smtp.login(smtpuser, smtppass) 
        smtp.sendmail(sender, receiver, msg.as_string()) 
        smtp.quit() 
    except Exception,e: 
        print (e)

實現端口掃描的程序,單線程版本nmscan.py

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

import nmap
import re
import mytools as tool
import sys

reload(sys)
sys.setdefaultencoding('utf8')


def nmScan(hostlist, portrange, whitelist):
    p = re.compile("^(\d*)\-(\d*)$")


    if type(hostlist) != list:
        help()
    portmatch = re.match(p, portrange)
    if not portmatch:
        help()
    l = []
    for host in hostlist:
        result = ''
    nm = nmap.PortScanner()
    tmp = nm.scan(host, portrange)
    result = result + "<h2>ip地址:%s 主機名:[%s]  ......  %s</h2><hr>" % (
    host, tmp['scan'][host]['hostname'], tmp['scan'][host]['status']['state'])
    try:
        ports = tmp['scan'][host]['tcp'].keys()
    except KeyError, e:
        if whitelist:
            whitestr = ','.join(whitelist)
            result = result + "未掃到開放端口!請檢查%s端口對應的服務狀態" % whitestr
        else:
            result = result + "掃描結果正常,無暴漏端口"
    for port in ports:
        info = ''
        if port not in whitelist:
            info = '<strong><font color=red>Alert:非預期端口</font><strong>&nbsp;&nbsp;'
        else:
            info = '<strong><font color=green>Info:正常開放端口</font><strong>&nbsp;&nbsp;'
        portinfo = "%s <strong>port</strong> : %s &nbsp;&nbsp;<strong>state</strong> : %s &nbsp;&nbsp;<strong>product<strong/> : %s <br>" % (
        info, port, tmp['scan'][host]['tcp'][port]['state'],
        tmp['scan'][host]['tcp'][port]['product'])
        result = result + portinfo
    l.append([host, str(result)])
    return l


def help():
    print ("Usage: nmScan(['127.0.0.1',],'0-65535')")


if __name__ == "__main__":
    hostlist = ['10.10.10.10', '10.10.10.11']
    portrange = '0-65535'
    whitelist = [80, 443]
    l = nmScan(hostlist, portrange, whitelist)
    sender = '995345781@qq.com'
    receiver = ['zhangyanlin8851@163.com', '877986976@qq.com']
    subject = '服務器端口掃描'
    smtpserver = 'smtp.exmail.qq.com'
    smtpuser = 'zhangyanlin8851@163.cn'
    smtppass = 'linuxidc163'
    mailcontent = ''
    for i in range(len(l)):
        mailcontent = mailcontent + l[i][1]
    tool.sendemail(sender, receiver, subject, mailcontent, smtpserver, smtpuser, smtppass)

多線程版本

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

import nmap
import re
import mytools as tool
import sys
from multiprocessing import Pool
from functools import partial

reload(sys)
sys.setdefaultencoding('utf8')


def nmScan(host, portrange, whitelist):
    p = re.compile("^(\d*)\-(\d*)$")
    # if type(hostlist) != list:
    #    help()
    portmatch = re.match(p, portrange)
    if not portmatch:
        help()

    if host == '121.42.32.172':
        whitelist = [25, ]
    result = ''
    nm = nmap.PortScanner()
    tmp = nm.scan(host, portrange)
    result = result + "<h2>ip地址:%s 主機名:[%s]  ......  %s</h2><hr>" % (
    host, tmp['scan'][host]['hostname'], tmp['scan'][host]['status']['state'])
    try:
        ports = tmp['scan'][host]['tcp'].keys()
        for port in ports:
            info = ''
            if port not in whitelist:
                info = '<strong><font color=red>Alert:非預期端口</font><strong>&nbsp;&nbsp;'
            else:
                info = '<strong><font color=green>Info:正常開放端口</font><strong>&nbsp;&nbsp;'
            portinfo = "%s <strong>port</strong> : %s &nbsp;&nbsp;<strong>state</strong> : %s &nbsp;&nbsp;<strong>product<strong/> : %s <br>" % (
            info, port, tmp['scan'][host]['tcp'][port]['state'], tmp['scan'][host]['tcp'][port]['product'])
            result = result + portinfo
    except KeyError, e:
        if whitelist:
            whitestr = ','.join(whitelist)
            result = result + "未掃到開放端口!請檢查%s端口對應的服務狀態" % whitestr
        else:
            result = result + "掃描結果正常,無暴漏端口"
    return result


def help():
    print ("Usage: nmScan(['127.0.0.1',],'0-65535')")
    return None


if __name__ == "__main__":
    hostlist = ['10.10.10.10', '10.10.10.11']
    portrange = '0-65535'
    whitelist = [80, 443]
    l = nmScan(hostlist, portrange, whitelist)
    sender = '75501664@qq.com'
    receiver = ['zhangyanlin8851@163.com', '877986976@qq.com']
    subject = '服務器端口掃描'
    smtpserver = 'smtp.exmail.qq.com'
    smtpuser = 'zhangyanlin8851@163.cn'
    smtppass = 'linuxidc163'
    mailcontent = ''
    for i in range(len(l)):
        mailcontent = mailcontent + l[i][1]
    tool.sendemail(sender, receiver, subject, mailcontent, smtpserver, smtpuser, smtppass)
相關文章
相關標籤/搜索