python nmap库用法

# -*- coding: utf8 -*-
from time import strftime, localtime
from datetime import timedelta, date
import time
import json
import datetime
import sqlite3
import os
import nmap
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
def nmapscan(ip):
    nm = nmap.PortScanner()
    nm.scan(hosts=ip,ports='80,3306,9200')
    print nm.scaninfo()
    print nm.command_line() 
    for host in nm.all_hosts():
        for proto in nm[host].all_protocols():
            lport = nm[host][proto].keys()
            lport.sort()
            count_port = len(lport)
            i = 0
            while i < count_port:
                in_port = lport[i]
                if nm[host][proto][in_port]['state'] == 'open':
                    print host + ":" + str(in_port) + " => " + nm[host][proto][in_port]['name']
                i+=1
if __name__ == '__main__':
    start = time.time()
    nmapscan('10.59.0.116')
    end = time.time()
    print "程序执行时间:" + str(int(end - start)) + "s"

执行结果为:
[root@server120 tmp]# python thread.py
{‘tcp’: {‘services’: ‘80,3306,9200’, ‘method’: ‘syn’}}
nmap -oX – -p 80,3306,9200 -sV 10.59.0.116
10.59.0.116:80 => http
10.59.0.116:9200 => wap-wsp
程序执行时间:90s

默认的执行参数如下:
nmap -oX – -p 80,3306,9200 -sV 10.59.0.116
使用-sV会尝试探测端口的服务类型/具体版本等信息,速度慢一些,可以尝试修改nmap参数
nm.scan(hosts=ip,arguments=’-sS -p 80,3306,9200′)
执行结果:
[root@server120 tmp]# python thread.py
{‘tcp’: {‘services’: ‘80,3306,9200’, ‘method’: ‘syn’}}
nmap -oX – -sS -p 80,3306,9200 10.59.0.116
10.59.0.116:80 => http
10.59.0.116:9200 => wap-wsp
程序执行时间:5s
可以看出执行时间缩短了很多