大批量端口掃描識(shí)別小工具

好久以前寫的小工具,很方便,結(jié)合了nmap、masscan、兩款工具,寫的一款快速掃描端口并識(shí)別服務(wù)的腳本,優(yōu)點(diǎn)是快、準(zhǔn)??梢詫P段、IP文件進(jìn)行大批量掃描,masscan用于端口掃描,nmap用于服務(wù)識(shí)別, requests用于獲取http協(xié)議的title,基于python3編寫,使用非常方便哦。


image.png

掃描結(jié)果輸出也進(jìn)行了一定排版優(yōu)化,非常直觀。
部分:


image.png
image.png

代碼如下:

# encoding=utf8
import sys
version = sys.version_info
if version < (3, 0):
    print('The current version is not supported, you need to use python3')
    sys.exit()
try:
    import datetime,json
    import threading,sys,getopt
    from threading import Semaphore
    import re,time,os
    import requests
    from bs4 import BeautifulSoup
    from requests.packages.urllib3.exceptions import InsecureRequestWarning
    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
except Exception as e:
    print('你有模塊未安裝,請使用pip3安裝,再執(zhí)行。')
    print(e)
    sys.exit()

nowTime=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
nowTime=str(nowTime).replace(' ','_').replace(':','-')

help="""nandM端口&服務(wù)極速掃描器 V1.3 by xiao 請確保系統(tǒng)中已安裝了 nmap、masscan、sudo。
-f      IP列表文件
-u      單個(gè)IP檢測
-p      掃描的端口                        默認(rèn):1-65535
-t      Masscan掃描端口的發(fā)包線程         默認(rèn):5000
-s      Nmap識(shí)別服務(wù)的線程                默認(rèn):1  識(shí)別服務(wù)線程建議5~30之間
--http  對開放的端口進(jìn)行Http協(xié)議訪問,獲取Title、StatusCode、DataSize    默認(rèn):不訪問

使用案例如下:
python3 nandM.py -f ip.txt
python3 nandM.py -u 198.13.36.73
python3 nandM.py -u 198.13.36.0/24  -t 5000                         #對IP段的全端口掃描并識(shí)別服務(wù),設(shè)置Masscan掃描端口的發(fā)包線程5000
python3 nandM.py -u 198.13.36.0/24  -p 80 -s 0 --http               # -s 0 代表不識(shí)別服務(wù),直接--http 訪問
python3 nandM.py -u 192.168.0.100-192.168.0.200 -p 22,80,445        # 對IP段的22、80、445端口掃描并識(shí)別服務(wù)
python3 nandM.py -u 192.168.0.100-192.168.0.200 -p 22,80,445 --http # 對IP段的22、80、445端口掃描并識(shí)別服務(wù),再http 訪問
 
"""
if len(sys.argv)<2:
    print(help)
    sys.exit()
file=''
postlist = '1-65535'        #掃描的端口
rate = '5000'
ScanServiceNub=1           #調(diào)用nmap識(shí)別服務(wù)的線程
HttpAccess=0               # file
httplist=[]
try:
    opts, args = getopt.getopt(sys.argv[1:], "f:u:t:p:s:h", ["http","help"])
    for opt, arg in opts:
        if "-f" == opt:
            print('IP文件:' + arg)
            file=str(arg)
        elif '-u'==opt:
            print('掃描目標(biāo):' + arg)
            ipu=str(arg)
        elif '-t' == opt:
            print('發(fā)包線程:' + arg)
            rate=str(arg)
        elif '-p' == opt:
            print('掃描端口:' + arg)
            postlist=str(arg)
        elif '-s' == opt:
            ScanServiceNub=arg
            if int(arg)==0:
                print('此次不識(shí)別服務(wù)')
            else:
                print('識(shí)別服務(wù)線程:' + arg)
        if opt in ("--http"):
            print('此次掃描會(huì)對開放的端口進(jìn)行http協(xié)議訪問')
            print('is http')
            HttpAccess=1
        if opt in ("-h", "--help"):
            print(help)
            sys.exit(1)
except getopt.GetoptError as e:
    print ('參數(shù)解析發(fā)生了錯(cuò)誤:' + e.msg)
    sys.exit(1)

if file=='':
    if ipu!='':
        print('\n開始掃描端口:\n'+'masscan ' + ipu + ' -p ' + postlist + ' --rate=' + rate + ' -oJ ' + nowTime + '.masccan\n')
        os.system('sudo masscan ' + ipu + ' -p ' + postlist + ' --rate=' + rate + ' -oJ ' + nowTime + '.masccan')
    else:
        sys.exit(1)
else:
    print('\n開始掃描端口:\n'+'sudo masscan   -iL '  +file+ '  -p ' + postlist + ' --rate=' + rate + ' -oJ ' + nowTime + '.masccan\n')
    os.system('sudo masscan  -iL ' + file + ' -p ' + postlist + ' --rate=' + rate + ' -oJ ' + nowTime + '.masccan')

count = 0
count2 = 0
da = open(nowTime + '.masccan', 'r', encoding='utf-8').read().split('\n')

if int(ScanServiceNub)==0:
    print('不掃描服務(wù)')
else:
    sem = Semaphore(int(ScanServiceNub))
    print('\n端口掃描完成,開啟多線程識(shí)別服務(wù): '+nowTime + '.masccan')
    if len(da) <= 1:
        print('沒有掃到任何端口,退出~~~~')
        sys.exit()  # 程序退出

sem2 = Semaphore(8)

def GetIpInformation(ip,sem2,fileres='null'):
    global count2
    try:
        if 'http' not in ip:
            ip='http://'+ip
        req=requests.get(url=ip,verify=False,timeout=8,stream=True)
        req.encoding=req.apparent_encoding
        datalen=len(req.text)
        suop = BeautifulSoup(req.text, 'html.parser')
        try:
            title=str(suop.title.text).strip()
        except Exception as e:
            title='title:Null'
        res={
            'IP': ip,
            'StatusCode':str(req.status_code),
            'Title':title,
            'DataSize':str(datalen)
        }
        print('IP: '+res['IP'],' | StatusCode: '+res['StatusCode'],' | Title: '+res['Title'],' | DataSize: '+res['DataSize']+' | ')
        #r = open(fileres, 'w').write('IP:'+res['IP'],' | StatusCode: '+res['StatusCode'],' | Title: '+res['Title'],' | DataSize: '+res['DataSize']+' | '+'\n')
    except Exception as e:
        print(ip,e)
    sem2.release()
    count2=count2-1
def scanserive(ip,port,sem):
    global count
    print('nmap  -sS -sV  -Pn -p '+port+ ' '+ip+' -->'+nowTime+'.nmap')
    os.system('sudo nmap  -sS  -sV -Pn -p '+port+ ' '+ip+' >>'+nowTime+'.nmap')
    count = count - 1
    sem.release()
    return 0

def outinfo(strinfo,status=0):#輸出不換行
    sys.stdout.write('\r識(shí)別服務(wù)線程,剩余'+str(strinfo)+'在執(zhí)行中')
    sys.stdout.flush()


def retext(file,filename='r.txt'):
    f = open(file, 'r',encoding='utf-8')
    string = ""
    matchIp = re.compile(r'(?<![\.\d])((?:(?:2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(?:2[0-4]\d|25[0-5]|[01]?\d\d?))(?![\.\d])')
    matchPort = re.compile(r'\d+/tcp\s+open')
    matchSer = re.compile(r'open\s+\w+.+')
    for line in f.readlines():
        m = ''.join(matchIp.findall(line))
        n = ''.join(matchPort.findall(line))[:-4]
        s = ''.join(matchSer.findall(line))[6:]
        if (m != ''):
            string += "ip:" + m
        if (n != ''):
            string += 'port:' + n
        if (s != ''):
            string += s + '\n'
        if (m != '' or n != '' or s != ''):
            string += '\n'
    r = open(filename, 'w')
    print("\n\n端口服務(wù)掃描完成,結(jié)果已保存在 "+filename+" 中,打印結(jié)果如下:\n"+string)
    r.write(string)
    r.close()
    f.close()
for data in da:
    if data !='' and 'finished' not in data:
        try:
            data=data.replace('},','}')
            list1 = json.loads(data)
            ip=list1['ip']
            port=list1['ports'][0]['port']
            httplist.append(str(ip)+':'+str(port))

            if int(ScanServiceNub) != 0:
                sem.acquire()
                count = count + 1
                threading.Thread(target=scanserive,args=(str(ip),str(port),sem,)).start()
        except Exception as e:
            pass

while True:
    if int(ScanServiceNub) != 0:
        outinfo(str(count))
    time.sleep(1)
    if count==0:#代表nmap服務(wù)識(shí)別結(jié)束。
        if int(ScanServiceNub) != 0:
            print('hack')
            retext(nowTime+'.nmap',nowTime+'.res')
        if HttpAccess==1:
            print('\nHTTP訪問結(jié)果如下:')
            for ah in httplist:
                sem2.acquire()
                count2=count2+1
                threading.Thread(target=GetIpInformation,args=(ah,sem2,nowTime+'.http',)).start()
            while True:
                if count2 == 0:
                    time.sleep(1)
                    if count2 == 0:
                        sys.exit()  # 程序退出
        else:
            sys.exit()  # 程序退出




最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容