個人電腦搭建服務器「掃描端口命令」

使用python模塊nmap,讀取excel數據對多個ip端口探活掃描

我一個響指下去,每個人都要少一個睾丸。。。

安全服務日常工作之大量端口狀態掃描

1、工欲善其事必先利其器。安裝python-nmap模塊。

pip list #cmd或powershell下 查看已安裝模塊,至於pip命令環境變量,自己解決 pip install python-nmap

編寫簡單的nmap單端口跑一下看看效果。
'''如果安裝了python-nmap模塊還不能使用,那就自行安裝nmap圖形化界面,然後添加到環境變量里,這樣就ok了,我的就是這樣;'''

import nmap   
np = nmap.PortScanner()  
a = np.scan(hosts='42.247.22.192',ports='80',arguments='-v -n -T4')
print(a)
安全服務日常工作之大量端口狀態掃描
安全服務日常工作之大量端口狀態掃描

返回結果: (重要的地方我已標紅,主要就是看返回端口狀態和服務名)

{'nmap': {'command_line': 'nmap -oX - -p 80 -v -n -T4 42.247.22.192', 'scaninfo': {'tcp': 
{'method': 'syn', 'services': '80'}}, 'scanstats': {'timestr': 'Thu Jun 10 11:31:57 2021', 
'elapsed': '1.72', 'uphosts': '1', 'downhosts': '0', 'totalhosts': '1'}}, 'scan': {'42.247.22.192': 
{'hostnames': [{'name': '', 'type': ''}], 'addresses': {'ipv4': '42.247.22.192'}, 'vendor': 
{}, 'status': {'state': 'up', 'reason': 'syn-ack'}, 'tcp': {80: {'state': 'open', 'reason': 'syn-ack', 'name': 'http',
'product': '', 'version': '', 'extrainfo': '', 'conf': '3', 'cpe': ''}}}}}
2、下面對得到的數據整理一下輸出,讓他看起來簡潔一些
import nmap   
np = nmap.PortScanner()  
a = np.scan(hosts='42.247.22.192',ports='80',arguments='-v -n -T4')
ip = '42.247.22.192'
for i in a['scan'][ip]['tcp'].keys():
    state = a['scan'][ip]['tcp'][i]['state']
    name = a['scan'][ip]['tcp'][i]['name'] 
    print(ip,i,state,name)
返回結果: 42.247.22.192 80 open http
安全服務日常工作之大量端口狀態掃描

看着整潔多了。

後面關於excel讀取和線程的代碼我直接貼了,今天事情多不細說了。。

3、使用python調用excel模塊和線程模塊,讀取excel數據,對多條數據進行掃描。

import nmap
import threading
from openpyxl import load_workbook
from xlwt import Workbook

wk = Workbook(encoding='utf-8')
wsheet = wk.add_sheet('Worksheet')
co = {}
ls = []
def read_excel_file():
    wb = load_workbook('test/diqu.xlsx')   #讀取excel文件
    # sheets = wb.get_sheet_names()
    # print(sheets)
    sheet = wb['暴露面資產全量']
    # print(sheet)
    m = sheet['G']      #讀取excelG列,我的G列是 ip:port,例:1.1.1.1:80

    for cell in m:            #這個for循環用於分割ip和端口,存到co字典
        # print(cell.value)
        mn = cell.value.split(':')
        if mn[0] in co:
            co[mn[0]].append(mn[1]) 
        else:     
            try:    
                co[mn[0]] = [mn[1]]
            except:
                co[mn[0]] = []

def thread(ip_port):       # 設置線程
    thread_num = threading.Semaphore(20)     # 設置線程數
    thread_list = []
    for IP, port in ip_port.items():        # 創建線程
        t = threading.Thread(target=nmap_ping_scan, args=(IP, port, thread_num,))
        thread_list.append(t)
        # print(t)
    for t in thread_list:     # 開始線程
        t.start()

    for t in thread_list:    # 等待線程
        t.join()
    print('線程結束')

def nmap_ping_scan(ip,port,thread_num):    #使用nmap掃描,結果存入ls列表
    global ls
    strport = ','.join(ports for ports in port)
    thread_num.acquire()          # 線程鎖
    try:
        nm = nmap.PortScanner()
        global result
        np = nm.scan(hosts=ip,ports=strport,arguments="-v -n -T4")
        for i in np['scan'][ip]['tcp'].keys():
            state = np['scan'][ip]['tcp'][i]['state']
            name = np['scan'][ip]['tcp'][i]['name']
            ls.extend([[ip,i,state,name]])
            # print(ip,i,state)
    except Exception as e:
        # print(e)
        pass
    thread_num.release()

def excel_write(ls):        #把ls列表的數據保存到新的excel中
    try:
        for u in range(len(ls)):
            p = 0
            for k in ls[u]:
                wsheet.write(u,p,k)
                p += 1
                # print(u,p,k)
    except:
        pass

if __name__ == '__main__':    #程序啟動
    read_excel_file()
    thread(co)
    excel_write(ls)
    # print(ls)
    wk.save('ceshi.xls')
    # nmap_dan_scan(co)
    # print(ls)
#ok,上述就是全部代碼了,上面是開了線程的,下面再加個單線程的方法吧
#使用方法,把def thread 和 def nmap_ping_scan 注釋掉
# 再最後if里把 nmap_dan_scan(co) 注釋解掉,上面倆個調用注釋掉就行。

def nmap_dan_scan(ip_port):    #單線程跑跑
    for ip,port in ip_port.items():
        strport = ','.join(ports for ports in port)
        try:
            nm = nmap.PortScanner()
            np = nm.scan(hosts=ip,ports=strport,arguments="-v -n -T4")
            for i in np['scan'][ip]['tcp'].keys():
                state = np['scan'][ip]['tcp'][i]['state']
                print(ip,i,state)
        except:
            pass   
掃描的結果大概就是這個樣子。
安全服務日常工作之大量端口狀態掃描

#注#如果不想使用腳本這麼麻煩的話,建議使用masscan命令比較簡潔,這個命令有時掃描會存在波動,大多情況下還是不錯的;(我是在centos下運行的)

寫個平時用的栗子:masscan -p0-65535 -iL ip.txt –rate=2000 > masscan-scan.txt

原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/205515.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
投稿專員的頭像投稿專員
上一篇 2024-12-07 17:47
下一篇 2024-12-07 17:47

相關推薦

發表回復

登錄後才能評論