一、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 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

四、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')

五、检测内网机器端口

定义函数库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)

实现端口扫描的程序,单线程版本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)

Python之NMAP详解的更多相关文章

  1. Python 字符串方法详解

    Python 字符串方法详解 本文最初发表于赖勇浩(恋花蝶)的博客(http://blog.csdn.net/lanphaday),如蒙转载,敬请保留全文完整,切勿去除本声明和作者信息.        ...

  2. python time模块详解

    python time模块详解 转自:http://blog.csdn.net/kiki113/article/details/4033017 python 的内嵌time模板翻译及说明  一.简介 ...

  3. Python中dict详解

    from:http://www.cnblogs.com/yangyongzhi/archive/2012/09/17/2688326.html Python中dict详解 python3.0以上,pr ...

  4. Python开发技术详解(视频+源码+文档)

    Python, 是一种面向对象.直译式计算机程序设计语言.Python语法简捷而清晰,具有丰富和强大的类库.它常被昵称为胶水语言,它能够很轻松的把用其他语言制作的各种模块(尤其是C/C++)轻松地联结 ...

  5. python/ORM操作详解

    一.python/ORM操作详解 ===================增==================== models.UserInfo.objects.create(title='alex ...

  6. 【python进阶】详解元类及其应用2

    前言 在上一篇文章[python进阶]详解元类及其应用1中,我们提到了关于元类的一些前置知识,介绍了类对象,动态创建类,使用type创建类,这一节我们将继续接着上文来讲~~~ 5.使⽤type创建带有 ...

  7. Python开发技术详解PDF

    Python开发技术详解(高清版)PDF 百度网盘 链接:https://pan.baidu.com/s/1F5J9mFfHKgwhkC5KuPd0Pw 提取码:xxy3 复制这段内容后打开百度网盘手 ...

  8. python之数据类型详解

    python之数据类型详解 二.列表list  (可以存储多个值)(列表内数字不需要加引号) sort s1=[','!'] # s1.sort() # print(s1) -->['!', ' ...

  9. Python环境搭建详解(Window平台)

    前言 Python,是一种面向对象的解释型计算机程序设计语言,是纯粹的自由软件,Python语法简洁清晰,特色是强制用空白符作为语句缩进,具有丰富和强大的库,它常被称为胶水语言. Python是一种解 ...

随机推荐

  1. 编程题1001.A+B Format (20)

    代码链接点击这里 由于有点久没写代码了,本次作业提交了三次才全部正解. 一开始以为是非常容易的题目,就没有带入多组数据,便以最简单的思路提交了代码. 发现了有特别多错误后,我并没有选择马上找同学帮忙, ...

  2. Ubuntu 64 + IntelliJ IDEA + Genymotion 搭建Android开发环境

    环境搭建所需可至 http://pan.baidu.com/s/1gd1Kf4Z 下载 注:     此处假定 Ubuntu 用户名为 chenfei     开发相关全部存放在 /home/chen ...

  3. 洛谷 P1251 餐巾计划问题(线性规划网络优化)【费用流】

    (题外话:心塞...大部分时间都在debug,拆点忘记加N,总边数算错,数据类型标错,字母写错......) 题目链接:https://www.luogu.org/problemnew/show/P1 ...

  4. 用php代码统计数据库中符合条件的行数

    $sql1 = "select count(*) from t_user where age<17"; $data1 = mysql_query($sql1); $rows1 ...

  5. 通过golang 查询impala

    cloudera官方没有提供impala基于golang的驱动,github有github.com/bippio/go-impala package main import ( "conte ...

  6. 20165318 《Java程序设计》实验一(Java开发环境的熟悉)实验报告

    20165318 <Java程序设计>实验一(Java开发环境的熟悉)实验报告 一.实验报告封面 课程:Java程序设计        班级:1653班        姓名:孙晓暄    ...

  7. 4027. [HEOI2015]兔子与樱花【树形DP】

    Description 很久很久之前,森林里住着一群兔子.有一天,兔子们突然决定要去看樱花.兔子们所在森林里的樱花树很特殊.樱花树由n个树枝分叉点组成,编号从0到n-1,这n个分叉点由n-1个树枝连接 ...

  8. ubuntu18.04 mariadb start失败

    在Ubuntu 安装mariadb 再restart 后出现错误 journalctl -xe 发现 apparmor权限问题 AppArmor 是一款与SeLinux类似的安全框架/工具,其主要作用 ...

  9. centos7 tengine 安装

    Tengine是由淘宝网发起的Web服务器项目.它在Nginx的基础上,针对大访问量网站的需求,添加了很多高级功能和特性.Tengine的性能和稳定性已经在大型的网站如淘宝网,天猫商城等得到了很好的检 ...

  10. Docker实战(十)之分布式处理与大数据平台

    分布式系统和大数据处理平台是目前业界关注的热门技术. 1.RabbitMQ RabbitMQ是一个支持AMQP的开源消息队列实现,由Erlang编写,因以高性能.高可用以及可伸缩性出名.它支持多种客户 ...