網路安全領域中,網路掃描扮演著至關重要的角色,用於識別目標主機的開放埠和服務。本文將介紹如何使用 Python 結合 Nmap 進行高效的網路掃描,並探討多執行緒埠掃描技術的實作細節。首先,我們將引導讀者安裝必要的 Python-nmap 模組,並示範如何使用該模組執行基本的網路掃描。接著,我們將解析 Nmap 掃描結果的結構和資訊,幫助讀者理解如何從結果中提取關鍵資訊。為了提升掃描效率,我們將探討 TCP 連線掃描的原理,並提供多執行緒埠掃描器的 Python 程式碼範例,其中包含動態調整執行緒數量和超時設定等最佳化策略。最後,我們將示範如何建立埠描述資料函式庫,以便在掃描結果中顯示更具體的服務資訊,提升掃描結果的可讀性和分析效率。

使用Python進行Nmap掃描

在網路安全領域中,掃描技術是一項重要的技能。本章節將介紹如何使用Python結合Nmap進行網路掃描。

為什麼使用Nmap?

Nmap是一款強大的網路掃描工具,用於檢測網路上的主機、服務和作業系統。它支援多種掃描技術,可以根據不同的需求進行組態。

Python-Nmap模組安裝

要使用Python控制Nmap,首先需要安裝python-nmap模組。可以使用pip進行安裝:

pip install python-nmap

安裝完成後,可以透過匯入nmap模組來驗證是否安裝成功:

import nmap

如果沒有出現錯誤訊息,則表示安裝成功。

使用Python-Nmap進行掃描

以下是使用python-nmap模組進行基本掃描的範例程式碼:

import nmap

nm = nmap.PortScanner()
nm.scan(hosts='192.168.0.1/24', arguments='-sS')

for host in nm.all_hosts():
    print('
---
-
---
-
---
-
---
-
---
-
---
-
---
-
---
-
---
-
---
-
---
-
---
-
---
-')
    print('Host : %s (%s)' % (host, nm[host].hostname()))
    print('State : %s' % nm[host].state())
    for proto in nm[host].all_protocols():
        print('
---
-
---
---
')
        print('Protocol : %s' % proto)

        lport = nm[host][proto].keys()
        sorted(lport)
        for port in lport:
            print ('port : %s\tstate : %s' % (port, nm[host][proto][port]['state']))

內容解密:

  1. 匯入nmap模組並建立PortScanner物件。
  2. 使用scan方法對指定的IP範圍進行掃描,這裡使用了-sS引數,表示進行TCP SYN掃描。
  3. 遍歷所有被掃描的主機,並列印出主機的狀態和開放的埠。

Nmap掃描結果解析

Nmap掃描結果是一個複雜的字典,包含了豐富的資訊。以下是結果的一部分範例:

'scan': {
    '192.168.0.1': {
        'status': {'state': 'up', 'reason': 'localhost-response'},
        'uptime': {'seconds': '7191', 'lastboot': 'Mon Mar 19 20:43:41 2018'},
        'vendor': {},
        'addresses': {'ipv4': '192.168.0.1'},
        'tcp': {
            902: {'product': '', 'state': 'open', 'version': '', 'name': 'iss-realsecure', 'conf': '3', 'extrainfo': '', 'reason': 'syn-ack', 'cpe': ''},
            135: {'product': '', 'state': 'open', 'version': '', 'name': 'msrpc', 'conf': '3', 'extrainfo': '', 'reason': 'syn-ack', 'cpe': ''},
            ...
        }
    }
}

內容解密:

  1. status欄位表示主機的狀態,例如是否線上。
  2. uptime欄位提供了主機的執行時間和最後一次重啟的時間。
  3. tcp欄位列出了開放的TCP埠及其相關資訊,如服務名稱和狀態。

在不同作業系統上執行Nmap掃描

本文展示了在不同作業系統(包括Linux和Windows)上執行Nmap掃描的結果。可以看到,Nmap能夠成功地識別出開放的TCP埠和作業系統資訊。

識別目標主機上的服務

透過掃描目標主機的埠,可以識別出正在執行的服務。埠號範圍從1到65535,其中1到1024是眾所周知的埠,通常用於特權服務。

埠掃描的概念

TCP的三次握手是埠掃描的基本原理。透過嘗試連線目標主機的不同埠,可以確定哪些埠是開放的。

簡單的埠掃描程式碼範例

以下是使用Python進行簡單埠掃描的範例程式碼:

import socket

def scan_port(ip, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(1)
        result = sock.connect_ex((ip, port))
        if result == 0:
            print(f'Port {port} is open')
        sock.close()
    except Exception as e:
        print(f'Error scanning port {port}: {e}')

# 範例用法
ip = '192.168.0.1'
for port in range(1, 1025):
    scan_port(ip, port)

內容解密:

  1. 建立一個socket物件,用於嘗試連線目標主機的指定埠。
  2. 使用connect_ex方法嘗試連線,如果傳回0,則表示埠開放。
  3. 遍歷指定的埠範圍,對每個埠進行掃描。

綜上所述,使用Python結合Nmap可以有效地進行網路掃描和服務識別。這對於網路安全管理、漏洞掃描和滲透測試等領域具有重要意義。

高效能埠掃描技術解析

在網路安全領域中,埠掃描是一項重要的偵測技術,用於識別目標主機開放的網路服務。一個高效能的埠掃描工具對於滲透測試和網路安全分析至關重要。

現有掃描工具的問題

傳統的埠掃描工具通常採用單執行緒模式,這種方式在面對大量埠掃描時效率低下。以下是一個基本的埠掃描器範例及其輸出結果:

from datetime import datetime
import socket

def scanport(host, start_port, end_port):
    try:
        for port in range(start_port, end_port):
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(1)
            result = sock.connect_ex((host, port))
            if result == 0:
                print(f"Port Open:--> {port}")
            sock.close()
    except Exception as e:
        print(e)

start_time = datetime.now()
host = input("Enter the remote host IP to scan:")
start_port = int(input("Enter the start port number:"))
end_port = int(input("Enter the last port number:"))
print("****************************************")
print(f"Mohit's Scanner is working on {host}")
print("****************************************")
scanport(host, start_port, end_port)
end_time = datetime.now()
print(f"scanning complete in {end_time - start_time}")

內容解密:

  1. 匯入必要的模組:使用datetime記錄掃描時間,socket進行網路連線。
  2. scanport函式:接受主機IP、起始埠和結束埠作為引數,遍歷指定範圍內的埠。
  3. 建立Socket連線:使用socket.socket()建立TCP Socket,並設定超時時間。
  4. 連線測試:透過connect_ex()方法測試與目標埠的連線,若傳回0表示埠開放。
  5. 記錄掃描時間:計算掃描開始與結束的時間差,輸出掃描耗時。

現有工具的效能問題

上述範例在掃描大量埠時效率較低,例如掃描4000個埠可能需要超過1小時。為提升效率,需採取多執行緒技術並最佳化超時設定。

高效能埠掃描器的設計考量

  1. 採用多執行緒技術:提高並發處理能力,加快掃描速度。
  2. 動態調整超時設定:根據網路狀況調整socket.setdefaulttimeout()的值。
  3. 支援主機名稱和網域名稱:擴充套件掃描器的適用範圍。
  4. 提供服務名稱與埠號:增強掃描結果的可讀性。
  5. 最佳化總體掃描時間:確保在合理時間內完成大量埠的掃描。

最佳化後的埠掃描器範例

from threading import Thread
import socket

def scan_port(host, port):
    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(0.5)
        result = sock.connect_ex((host, port))
        if result == 0:
            print(f"Port {port} is open")
        sock.close()
    except Exception as e:
        pass

def main():
    host = input("Enter the remote host IP to scan:")
    start_port = int(input("Enter the start port number:"))
    end_port = int(input("Enter the last port number:"))
    threads = []
    for port in range(start_port, end_port):
        thread = Thread(target=scan_port, args=(host, port))
        threads.append(thread)
        thread.start()
    for thread in threads:
        thread.join()

if __name__ == "__main__":
    main()

內容解密:

  1. scan_port函式:針對單一埠進行掃描,使用多執行緒提高效率。
  2. main函式:負責建立多個執行緒,每個執行緒呼叫scan_port掃描不同埠。
  3. 超時設定:將超時時間設為0.5秒,以平衡效率和準確性。
  4. 執行緒管理:透過join()方法確保所有執行緒完成後再結束主程式。

網路掃描與多執行緒埠掃描技術深度解析

網路掃描的核心目的與技術挑戰

網路掃描是網路安全領域的重要技術手段,主要用於收集網路、主機及其服務的相關資訊。傳統的ping指令掃描方法雖然簡單易用,但容易受到ICMP封包過濾或防火牆阻擋的限制。在這種情況下,TCP三向交握掃描技術成為有效的替代方案。

TCP連線掃描的技術原理

TCP連線掃描的核心在於利用TCP/IP協定堆疊的特性,透過特定的埠連線嘗試來判斷目標主機的服務狀態。某些Windows系統的特定埠預設保持開放狀態,為掃描提供了可利用的技術切入點。

多執行緒埠掃描器的設計與實作

為提升掃描效率,多執行緒技術被廣泛應用於埠掃描器的設計中。以下是一個完整的Python實作範例:

import threading
import socket

# 資料函式庫檔案相關設定
database_file = "port_description.dat"
file_name = raw_input("Enter the file name: ")
# 開啟並讀取檔案內容
with open(file_name, 'r') as f:
    # 處理檔案內容
    dict1 = {}
    for line in f:
        key, value = line.strip().split(' ', 1)
        dict1[int(key)] = value.strip()

# 將字典儲存為pickle檔案
import pickle
with open(database_file, 'wb') as pfile:
    pickle.dump(dict1, pfile)
print("Dictionary is created")

# 多執行緒埠掃描器實作
class PortScanner(threading.Thread):
    def __init__(self, target_ip, start_port, end_port):
        threading.Thread.__init__(self)
        self.target_ip = target_ip
        self.start_port = start_port
        self.end_port = end_port

    def run(self):
        for port in range(self.start_port, self.end_port + 1):
            try:
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(1)
                result = sock.connect_ex((self.target_ip, port))
                if result == 0:
                    print(f"Port Open:--> {port}")
                sock.close()
            except Exception as e:
                print(f"Error scanning port {port}: {e}")

# 主程式執行邏輯
def main():
    target_ip = input("Enter the IP Address to scan: ")
    start_port = int(input("Enter the start port number: "))
    end_port = int(input("Enter the last port number: "))
    connectivity = input("For low connectivity press L and High connectivity Press H: ")
    
    # 根據連線型別調整執行緒數量
    if connectivity.lower() == 'l':
        thread_count = 10
    else:
        thread_count = 50
    
    # 計算每個執行緒負責的埠範圍
    ports_per_thread = (end_port - start_port + 1) // thread_count
    
    threads = []
    for i in range(thread_count):
        thread_start_port = start_port + i * ports_per_thread
        thread_end_port = thread_start_port + ports_per_thread - 1
        if i == thread_count - 1:
            thread_end_port = end_port
        
        thread = PortScanner(target_ip, thread_start_port, thread_end_port)
        threads.append(thread)
        thread.start()

    for thread in threads:
        thread.join()

if __name__ == "__main__":
    main()

程式碼關鍵解析:

  1. 多執行緒設計:透過將埠範圍分配給多個執行緒,顯著提升掃描效率。
  2. 連線型別調整:根據使用者選擇的連線型別(低/高連線)動態調整執行緒數量。
  3. 埠範圍計算:精確計算每個執行緒負責的埠範圍,確保完整覆寫目標埠區間。
  4. 錯誤處理機制:實作了完善的例外處理,確保掃描過程的穩定性。

效能最佳化與實際應用

實驗結果表明,多執行緒埠掃描器相比單執行緒版本,在掃描效率上有顯著提升。在實際應用中,應根據目標網路環境和系統資源合理調整執行緒數量,以達到最佳的掃描效能。

資料函式庫檔案建立與應用

埠描述資料函式庫檔案的建立是透過將文字檔案中的埠資訊轉換為pickle格式實作的。這種二進位制儲存方式不僅提高了資料讀取效率,也為後續的埠資訊查詢提供了便利。

建立pickle資料函式庫檔案:

import pickle

# 開啟原始文字檔案並讀取內容
with open('port_descriptions.txt', 'r') as file:
    port_dict = {}
    for line in file:
        # 解析並儲存埠描述資訊
        key, value = line.strip().split(' ', 1)
        port_dict[int(key)] = value.strip()

# 將字典儲存為pickle檔案
with open('port_description.dat', 'wb') as pfile:
    pickle.dump(port_dict, pfile)