1. 程式人生 > >利用nmap進行特定端口掃描

利用nmap進行特定端口掃描

RoCE ner can lac [] reduce ejs The urn

1.使用Python的nmap進行特定的端口掃描,包括各種常用的數據庫端口,web端口,一些自定義的端口,使用nmap之前需要確定本機已經安裝了nmap包
2.其中ret()函數是獲取ip列表
3.最後print出來的是一個json的結果,方便使用zabbix進行監控
4.因為ip較多,需要進行多線程獲取結果,時間比較久,建議先把結果寫到本地,然後再用zabbix進行自動發現並監控
5.Python語法不夠精通,歡迎批評指導

#!/usr/bin/python 
#-*-coding:utf-8-*-
import json 
import sys 
import nmap
import multiprocessing
import commands
import urllib2
import time
reload(sys)
sys.setdefaultencoding(‘utf8‘)

def ret():
    url=commands.getoutput(‘/bin/bash /cron/md5_ops_exist_InZabbix_monitor.sh‘)
    #ip列表
    url_data=urllib2.urlopen(url,timeout=50)
    ipList = json.loads(url_data.readline())
    url_data.close()
    allip=ipList["data"]["all"]
#    opsip = [i.strip(‘u‘) for i in allip]
    return allip

def checkPythonVersionGt():
    #python version great then 2.4?
    pythonVersion = sys.version_info
    if pythonVersion[0] == 2 and pythonVersion[1] > 5:
        return True
    else:
        return False

if checkPythonVersionGt():
    import subprocess
    import json
else:
    try:
        import simplejson
    except ImportError:
        os.system(‘yum -y install python-simplejson ‘)

def resoutput(ipList):
    #output result
    if checkPythonVersionGt():
        printt= (json.dumps(ipList,indent=4,separators=(‘,‘,‘:‘)))
    else:
        try:
            import simplejson

            printt= (simplejson.dumps(ipList,indent=4,separators=(‘,‘,‘:‘)))
        except ImportError:
            printt=  (str(ipList))
    return printt

def scan_defaults_ports(ip,default_ports):
    nm=nmap.PortScanner()
    sd={}
    productname={}
    nm.scan(ip,default_ports)
    alll={}
    po=[]
    for host in nm.all_hosts():
        if nm[host].has_key(‘tcp‘):
            for port in nm[host][‘tcp‘].keys():
                name  = nm[host][‘tcp‘][port][‘name‘]
                state = nm[host][‘tcp‘][port][‘state‘]
                if  state == ‘open‘:
                    po.append(port)
    if len(po)>0:
        po=‘,‘.join(str(s) for s in po)
        sd[host]=po
        return sd
    else:
        return

def default_ports():
    p1="21 22 677 873 80 8080"
    p2=" ".join(map(str,[k for k in range(3306,3321)])) 
    p3=" ".join(map(str,[k for k in range(3690,3692)]))
    p4=" ".join(map(str,[k for k in range(6379,6400)]))
    p5=" ".join(map(str,[k for k in range(11200,11201)]))
    p6=" ".join(map(str,[k for k in range(27000,27101)]))
    p7=" ".join(map(str,[k for k in range(20000,20101)]))
    p8=" ".join(map(str,[k for k in range(22000,22101)]))
    default_ports=reduce(lambda x,y: x+‘ ‘+y,[p1,p2,p3,p4,p5,p6,p7,p8]).replace(" ",",")
    return default_ports

if __name__==‘__main__‘:
    pool = multiprocessing.Pool(processes = 3)
    result=[]
    default_ports=default_ports()
    opsip=ret()
    for x in opsip: 
        try:
            x=x.encode(‘utf-8‘)
            result.append(pool.apply_async(scan_defaults_ports, (x,default_ports)))
        except Exception as e:
            print e
            pass
    pool.close()
    pool.join()
    ip=[]
    for res in result:
        ip.append(res.get())
    ip=filter(None,ip)
    iplist=[]
    outip={}
    for i in ip:
        k=i.keys()
        v=i.values()
        k=‘,‘.join(str(s) for s in k)
        v=‘,‘.join(str(s) for s in v)
        iplist.append({‘{#NEWSACNPORT}‘:v,‘{#NEWSCANHOSTIP}‘:k})
    outip={‘data‘:iplist}
    outip= resoutput({‘data‘:iplist})
    print outip

利用nmap進行特定端口掃描