Created
September 17, 2025 00:17
-
-
Save freelze/3b2c1bacb1bb863cd1e1ff92f89ac7ee to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # 建立 generate_ip_table.sh 腳本檔案 | |
| cat << 'EOF' > generate_ip_table.sh | |
| #!/bin/bash | |
| # 這是一個用來從 DHCP 租約列表中查找 IP 地址的腳本 | |
| # 定義輸入和輸出檔案的名稱,這樣更容易修改 | |
| LEASE_FILE="dhcp_lease_list.txt" | |
| MAC_FILE="MAC_TABLE.txt" | |
| OUTPUT_FILE="IP_table.txt" | |
| # 檢查必要的輸入檔案是否存在 | |
| if [ ! -f "$LEASE_FILE" ] || [ ! -f "$MAC_FILE" ]; then | |
| echo "錯誤: 輸入檔案 $LEASE_FILE 或 $MAC_FILE 不存在。" | |
| exit 1 | |
| fi | |
| echo "正在根據 $MAC_FILE 從 $LEASE_FILE 中查找 IP..." | |
| # --- 核心邏輯 --- | |
| # 使用 awk 執行查找和格式化 | |
| # awk 會依序讀取 LEASE_FILE 和 MAC_FILE | |
| awk ' | |
| # 第一階段: 讀取 dhcp_lease_list.txt (當 FNR==NR 時) | |
| FNR==NR { | |
| # 只處理包含 MAC 地址的行 (簡單地用 ":" 判斷) | |
| if ($1 ~ /:/) { | |
| # 建立一個陣列 (類似 Python 的字典), 鍵是 MAC (欄位1),值是 IP (欄位2) | |
| leases[$1] = $2 | |
| } | |
| next # 讀取下一行,並跳過後面的程式碼區塊 | |
| } | |
| # 第二階段: 讀取 MAC_TABLE.txt (當 FNR!=NR 時) | |
| { | |
| # 檢查當前行的 MAC 地址 ($1) 是否存在於我們建立的陣列中 | |
| if ($1 in leases) { | |
| # NR 是總行號, FNR 是當前檔案行號。 NR-FNR 可以計算出第二個檔案的行號 | |
| # 使用 printf 格式化輸出: %02d (補零到兩位數的整數), %s (字串) | |
| printf "%02d,%s\n", (NR - FNR), leases[$1] | |
| } | |
| } | |
| ' "$LEASE_FILE" "$MAC_FILE" > "$OUTPUT_FILE" | |
| echo "處理完成!結果已儲存到 $OUTPUT_FILE" | |
| EOF |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment