python-nmap使用及案例

nmap概念及功能

概念

NMap,也就是Network Mapper,最早是Linux下的网络扫描和嗅探工具包。

nmap是一个网络连接端扫描软件,用来扫描网上电脑开放的网络连接端。确定哪些服务运行在哪些连接端,并且推断计算机运行哪个操作系统(这是亦称 fingerprinting)。它是网络管理员必用的软件之一,以及用以评估网络系统安全。

正如大多数被用于网络安全的工具,nmap 也是不少黑客及骇客(又称脚本小子)爱用的工具 。系统管理员可以利用nmap来探测工作环境中未经批准使用的服务器,但是黑客会利用nmap来搜集目标电脑的网络设定,从而计划攻击的方法。

Nmap 常被跟评估系统漏洞软件Nessus 混为一谈。Nmap 以隐秘的手法,避开闯入检测系统的监视,并尽可能不影响目标系统的日常操作。

Nmap 在黑客帝国(The Matrix)中,连同SSH1的32位元循环冗余校验漏洞,被崔妮蒂用以入侵发电站的能源管理系统。

功能

基本功能有三个,一是探测一组主机是否在线;其次是扫描 主机端口,嗅探所提供的网络服务;还可以推断主机所用的操作系统 。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

nmap安装

本文以linux Ubuntu16.04为例,最后主要用python操作

1. 先安装nmap

sudo apt-get install nmap

2.再安装python-nmap

sudo pip install python-nmap

安装完之后python导入nmap测试验证是否成功

[email protected]:~# python
Python 2.7.12 (default, Jul  1 2016, 15:12:24)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import nmap

python操作nmap

1.简单的小案例

创建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‘: ‘‘}
}
}
}
}

2.内置方法:

还可以打印出简单的信息

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‘) 

更多操作请进官网http://xael.org/pages/python-nmap-en.html

实验案例

检测内网机器端口

1.定义函数库mytools.py

#-*- 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

2. 实现端口扫描的程序,单线程版本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 = ‘[email protected]‘
    receiver = [‘[email protected]‘, ‘[email protected]‘]
    subject = ‘服务器端口扫描‘
    smtpserver = ‘smtp.exmail.qq.com‘
    smtpuser = ‘[email protected]‘
    smtppass = ‘linuxidc163‘
    mailcontent = ‘‘
    for i in range(len(l)):
        mailcontent = mailcontent + l[i][1]
    tool.sendemail(sender, receiver, subject, mailcontent, smtpserver, smtpuser, smtppass)

3.多线程版本

# !/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 = ‘[email protected]‘
    receiver = [‘[email protected]‘, ‘[email protected]‘]
    subject = ‘服务器端口扫描‘
    smtpserver = ‘smtp.exmail.qq.com‘
    smtpuser = ‘[email protected]‘
    smtppass = ‘linuxidc163‘
    mailcontent = ‘‘
    for i in range(len(l)):
        mailcontent = mailcontent + l[i][1]
    tool.sendemail(sender, receiver, subject, mailcontent, smtpserver, smtpuser, smtppass)

 

时间: 2024-08-25 22:08:13

python-nmap使用及案例的相关文章

基于Python数据分析与机器学习案例实战教程

课程--基于Python数据分析与机器学习案例实战教程 分享网盘下载--https://pan.baidu.com/s/1jHSaRAY 密码: xk37 课程背景基于数据分析与机器学习领域,使用python作为课程的实战语言,随着大数据与人工智能领域日益火爆,数据分析和机器学习建模成了当下最热门的技术,课程旨在帮助同学们快速掌握python数据分析包以及经典机器学习算法并通过对真实数据集分析进行实战演示. 课程风格通俗易懂,基于真实数据集案例实战. 主体课程分成三个大模块 (1)python数

Python网络爬虫实战案例之:7000本电子书下载(2)

一.前言 本文是<Python开发实战案例之网络爬虫>的第二部分:7000本电子书下载网络爬虫开发环境安装部署.配套视频课程详见51CTO学院. 二.章节目录 (1)Python开发环境依赖(2)Python依赖程序安装(3)Requests-html安装(4)Requests-html 源码框架下载(5)Requests-html 开发指导手册 三.正文 3.1 Python开发环境依赖 3.2 Python依赖程序安装 3.3 requests-html安装 3.4 requests-ht

Python网络爬虫实战案例之:7000本电子书下载(3)

一.前言 本文是<Python开发实战案例之网络爬虫>的第三部分:7000本电子书下载网络爬虫开发实战详解.配套视频课程详见51CTO学院请添加链接描述. 二.章节目录 3.1 业务流程3.2 页面结构分析:目录页3.3 页面结构分析:详情页3.4 页面请求和响应:目录页4.5 页面请求和响应:详情页3.4 三.正文 3.1 业务流程 3.2.1 页面结构分析-目录页 3.2.2 页面结构分析-详情页 3.3 页面请求与解析-目录页 3.4 页面请求与解析-详情页 3.5 文件下载 四.未完待

Python网络爬虫实战案例之:7000本电子书下载(4)

一.前言 本文是<Python开发实战案例之网络爬虫>的第四部分:7000本电子书下载网络爬虫-源码框架剖析.配套视频课程详见:51CTO学院. 二.章节目录 3.1 requests-html文件结构3.2 requests-html源码框架3.3 导入依赖库3.4 HTMLSession请求类3.5 HTMLResponse请求响应类3.6 HTML页面结构类 三.正文 3.1 requests-html 文件结构 3.2 requests-html源码框架 3.3 导入依赖库 3.4 H

python(nmap模块、多线程模块)

http://xael.org/pages/python-nmap-en.html       nmap模块 http://www.tutorialspoint.com/python/python_multithreading.htm   多线程 http://www.cnblogs.com/tqsummer/archive/2011/01/25/1944771.html 多线程

Python字典的入门案例

查看python版本: [[email protected] ~]# python -V Python 2.7.5 1.基本的字典操作 案例1:简单电话本实现 [[email protected] ~]# vim addresslist.py # -*- coding: utf-8 -*- #一个简单的数据库通讯录 #字典使用人名作为键.每个人使用另一个字典来表示,其键'phone'和‘addr’分别表示电话号码和地址 people = { 'Wang':{ 'phone':'12345', '

Python爬虫(十一)_案例:使用正则表达式的爬虫

本章将结合先前所学的爬虫和正则表达式知识,做一个简单的爬虫案例,更多内容请参考:Python学习指南 现在拥有了正则表达式这把神兵利器,我们就可以进行对爬取到的全部网页源代码进行筛选了. 下面我们一起尝试一下爬取内涵段子网站: http://www.neihan8.com/article/list_5_1.html 打开之后,不难看出里面一个一个非常有内涵的段子,当你进行翻页的时候,注意url地址的变化: 第一页url: http: //www.neihan8.com/article/list_

Python爬虫(十三)_案例:使用XPath的爬虫

本篇是使用XPath的案例,更多内容请参考:Python学习指南 案例:使用XPath的爬虫 现在我们用XPath来做一个简单的爬虫,我们尝试爬取某个贴吧里的所有帖子且将该帖子里每个楼层发布的图片下载到本地. #-*- coding:utf-8 -*- #tieba_xpath.py """ 作用:本案例使用XPath做一个简单的爬虫,我们尝试爬去某个贴吧的所有帖子 """ import os import urllib2 import urll

python协程gevent案例:爬取斗鱼美女图片

分析 分析网站寻找需要的网址 用谷歌浏览器摁F12打开开发者工具,然后打开斗鱼颜值分类的页面,如图: 在里面的请求中,最后发现它是以ajax加载的数据,数据格式为json,如图: 圈住的部分是我们需要的数据,然后复制它的网址为https://www.douyu.com/gapi/rknc/directory/yzRec/1,出于学习目的只爬取第一页(减少服务器压力).然后把网址放到浏览器中测试是否可以访问.如图: 结果正常. 分析json数据,提取图片链接 最后分析发现json中的data里面的

python Pillow 的简单案例

#代码来自 实验楼https://www.shiyanlou.com/courses/ #encoding=utf-8#/usr/bin/env pythonfrom PIL import Imageimport argparse parser = argparse.ArgumentParser() parser.add_argument('file')parser.add_argument('-o' , '--output')parser.add_argument('--width', typ