Deepseek對程式的理解度似乎還不錯,在此用一個最近的工程小問題尋求協助
Q1: 用 python 寫個 CVE維護工具
CVE(Common Vulnerabilities and Exposures)是公開的資訊安全漏洞資料庫。維護一個 CVE 資料庫通常涉及以下步驟:
- 獲取 CVE 資料 :從官方來源(如 NVD)獲取 CVE 資料。
- 解析和儲存資料 :將資料解析並儲存到本地資料庫或檔案中。
- 定期更新 :定期檢查並更新 CVE 資料。
- 查詢和報告 :提供查詢功能,並生成報告。
以下是一個簡單的 Python 腳本,用於從 NVD 獲取 CVE 資料並將其儲存到本地 JSON 檔案中。這個腳本可以作為 CVE 維護的基礎。
1. 安裝必要的套件
首先,安裝所需的 Python 套件:
pip install requests
2. 獲取 CVE 資料並儲存到本地
以下是一個簡單的 Python 腳本,用於從 NVD 獲取 CVE 資料並將其儲存到本地 JSON 檔案中:
import requests
import json
from datetime import datetime
# NVD API URL
NVD_API_URL = "https://services.nvd.nist.gov/rest/json/cves/1.0"
def fetch_cves(start_index=0, results_per_page=2000):
params = {
"startIndex": start_index,
"resultsPerPage": results_per_page
}
response = requests.get(NVD_API_URL, params=params)
if response.status_code == 200:
return response.json()
else:
print(f"Failed to fetch data: {response.status_code}")
return None
def save_cves_to_file(cves, filename="cves.json"):
with open(filename, "w") as file:
json.dump(cves, file, indent=4)
print(f"CVEs saved to {filename}")
def main():
# Fetch CVEs from NVD
cves = fetch_cves()
if cves:
# Save CVEs to a JSON file
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"cves_{timestamp}.json"
save_cves_to_file(cves, filename)
if __name__ == "__main__":
main()
3. 定期更新
你可以使用 cron job(在 Linux 上)或 Task Scheduler(在 Windows 上)來定期執行這個腳本,以確保 CVE 資料是最新的。
4. 查詢和報告
你可以擴展這個腳本,添加查詢功能來搜索特定的 CVE,或者生成報告來顯示最新的漏洞。
例如,以下是一個簡單的查詢功能:
def search_cve_by_id(cve_id, filename="cves.json"):
with open(filename, "r") as file:
cves = json.load(file)
for cve in cves["result"]["CVE_Items"]:
if cve["cve"]["CVE_data_meta"]["ID"] == cve_id:
return cve
return None
# Example usage
cve_id = "CVE-2021-34527" # Example CVE ID
cve = search_cve_by_id(cve_id)
if cve:
print(json.dumps(cve, indent=4))
else:
print(f"CVE {cve_id} not found.")
5. 進一步擴展
- 資料庫儲存 :將 CVE 資料儲存到 SQLite、MySQL 或其他資料庫中,以便更高效地查詢和管理。
- 自動化報告 :定期生成報告,並通過電子郵件發送給相關人員。
- 漏洞掃描 :結合漏洞掃描工具,自動檢測系統中的漏洞並與 CVE 資料庫進行比對。
這個腳本只是一個基礎的實現,實際的 CVE 維護系統可能需要更多的功能和更複雜的邏輯。
Q2: 可以掃描 工程並輸出 excel 報表, 可以利用 cve-bin-tool
cve-bin-tool 是一個用於掃描軟體相依性並檢測已知 CVE 漏洞的工具。它可以掃描專案中的二進位檔案或相依性,並輸出包含 CVE 資訊的報告。結合 Python,我們可以進一步將掃描結果輸出為 Excel 報表。
以下是實現步驟:
1. 安裝必要的套件
首先,安裝 cve-bin-tool 和用於生成 Excel 的 openpyxl:
pip install cve-bin-tool openpyxl
2. 使用 cve-bin-tool 掃描專案
cve-bin-tool 提供了一個命令行工具,但我們也可以通過 Python 直接調用它來掃描專案。
以下是一個示例腳本,用於掃描專案並將結果輸出為 Excel 報表:
import subprocess
import json
from openpyxl import Workbook
def scan_project_with_cve_bin_tool(project_path):
"""
使用 cve-bin-tool 掃描專案,並返回 JSON 格式的掃描結果。
"""
try:
# 執行 cve-bin-tool 掃描
result = subprocess.run(
["cve-bin-tool", "-q", "-f", "json", project_path],
capture_output=True,
text=True
)
if result.returncode == 0:
# 解析 JSON 輸出
return json.loads(result.stdout)
else:
print("掃描失敗:", result.stderr)
return None
except Exception as e:
print("發生錯誤:", str(e))
return None
def save_to_excel(data, output_file="cve_report.xlsx"):
"""
將掃描結果保存為 Excel 文件。
"""
if not data:
print("沒有數據可保存。")
return
# 創建 Excel 工作簿
wb = Workbook()
ws = wb.active
ws.title = "CVE 報告"
# 添加表頭
headers = ["產品", "版本", "CVE ID", "嚴重性", "描述", "CVSS 分數"]
ws.append(headers)
# 添加數據
for entry in data:
product = entry.get("product", "")
version = entry.get("version", "")
cve_id = entry.get("cve_number", "")
severity = entry.get("severity", "")
description = entry.get("description", "")
cvss_score = entry.get("CVSS_version", {}).get("score", "")
ws.append([product, version, cve_id, severity, description, cvss_score])
# 保存文件
wb.save(output_file)
print(f"報告已保存到 {output_file}")
def main():
# 掃描專案路徑
project_path = input("請輸入專案路徑: ")
# 掃描專案
scan_results = scan_project_with_cve_bin_tool(project_path)
if scan_results:
# 保存為 Excel
save_to_excel(scan_results)
if __name__ == "__main__":
main()
3. 運行腳本
- 將上述代碼保存為
cve_scan.py。 -
運行腳本並輸入要掃描的專案路徑:
bash复制
python cve_scan.py -
腳本會掃描專案並生成一個名為
cve_report.xlsx的 Excel 文件,包含以下欄位:- 產品 :受影響的軟體名稱。
- 版本 :受影響的版本。
- CVE ID :CVE 編號。
- 嚴重性 :漏洞的嚴重性(如 HIGH、MEDIUM、LOW)。
- 描述 :漏洞的詳細描述。
- CVSS 分數 :漏洞的 CVSS 分數。
4. 進一步擴展
- 自定義掃描選項 :
cve-bin-tool支持多種掃描選項,例如指定掃描深度、忽略特定 CVE 等。可以通過修改subprocess.run的參數來實現。 - 自動化掃描 :將此腳本與 CI/CD 工具(如 Jenkins、GitHub Actions)集成,實現自動化掃描和報告生成。
- 郵件通知 :使用
smtplib將生成的 Excel 報告通過電子郵件發送給相關人員。
5. 示例輸出
生成的 Excel 文件可能如下所示:
| 產品 | 版本 | CVE ID | 嚴重性 | 描述 | CVSS 分數 |
|---|---|---|---|---|---|
| openssl | 1.1.1k | CVE-2021-3450 | HIGH | 漏洞描述… | 9.8 |
| curl | 7.64.0 | CVE-2021-22947 | MEDIUM | 漏洞描述… | 6.5 |
| python | 3.8.10 | CVE-2021-3177 | LOW | 漏洞描述… | 3.7 |
通過這種方式,你可以輕鬆掃描專案中的 CVE 漏洞並生成易於閱讀的 Excel 報表。
Q3: 可以手動維護 remarks 與 comments 欄位並更新
為了手動維護 remarks 和 comments 欄位並更新 CVE 報告,我們可以擴展之前的腳本,使其支持以下功能:
- 加載現有的 CVE 報告 (如果存在)。
- 允許用戶手動輸入或更新
remarks和comments欄位 。 - 保存更新後的報告 。
以下是實現步驟:
1. 安裝必要的套件
確保已安裝以下套件:
pip install openpyxl
2. 擴展腳本以支持手動維護
以下是完整的 Python 腳本,支持加載現有報告、手動更新 remarks 和 comments 欄位,並保存更新後的報告:
import json
from openpyxl import Workbook, load_workbook
def load_existing_report(file_path):
"""
加載現有的 Excel 報告。
"""
try:
wb = load_workbook(file_path)
ws = wb.active
data = []
# 讀取數據
for row in ws.iter_rows(min_row=2, values_only=True): # 跳過表頭
data.append({
"產品": row[0],
"版本": row[1],
"CVE ID": row[2],
"嚴重性": row[3],
"描述": row[4],
"CVSS 分數": row[5],
"Remarks": row[6] if len(row) > 6 else "",
"Comments": row[7] if len(row) > 7 else ""
})
return data
except FileNotFoundError:
print("未找到現有報告,將創建新報告。")
return None
def update_remarks_and_comments(data):
"""
手動更新 remarks 和 comments 欄位。
"""
for i, entry in enumerate(data):
print(f"\nCVE ID: {entry['CVE ID']}")
print(f"產品: {entry['產品']}, 版本: {entry['版本']}")
print(f"當前 Remarks: {entry.get('Remarks', '')}")
print(f"當前 Comments: {entry.get('Comments', '')}")
remarks = input("輸入新的 Remarks(留空以保持不變): ").strip()
comments = input("輸入新的 Comments(留空以保持不變): ").strip()
if remarks:
entry["Remarks"] = remarks
if comments:
entry["Comments"] = comments
return data
def save_to_excel(data, output_file="cve_report_updated.xlsx"):
"""
將更新後的數據保存為 Excel 文件。
"""
wb = Workbook()
ws = wb.active
ws.title = "CVE 報告"
# 添加表頭
headers = ["產品", "版本", "CVE ID", "嚴重性", "描述", "CVSS 分數", "Remarks", "Comments"]
ws.append(headers)
# 添加數據
for entry in data:
ws.append([
entry["產品"],
entry["版本"],
entry["CVE ID"],
entry["嚴重性"],
entry["描述"],
entry["CVSS 分數"],
entry.get("Remarks", ""),
entry.get("Comments", "")
])
# 保存文件
wb.save(output_file)
print(f"更新後的報告已保存到 {output_file}")
def main():
# 加載現有報告
report_file = input("請輸入現有報告的文件路徑(留空以創建新報告): ").strip()
if report_file:
data = load_existing_report(report_file)
else:
data = []
if not data:
print("未加載到數據,請手動輸入 CVE 數據。")
data = []
while True:
entry = {
"產品": input("產品: "),
"版本": input("版本: "),
"CVE ID": input("CVE ID: "),
"嚴重性": input("嚴重性: "),
"描述": input("描述: "),
"CVSS 分數": input("CVSS 分數: "),
"Remarks": input("Remarks: "),
"Comments": input("Comments: ")
}
data.append(entry)
if input("是否繼續添加?(y/n): ").strip().lower() != 'y':
break
# 更新 remarks 和 comments
data = update_remarks_and_comments(data)
# 保存更新後的報告
save_to_excel(data)
if __name__ == "__main__":
main()
3. 運行腳本
- 將上述代碼保存為
cve_report_updater.py。 -
運行腳本:
bash复制
python cve_report_updater.py - 如果存在現有報告,輸入報告的文件路徑;否則,可以手動輸入 CVE 數據。
- 腳本會提示你為每個 CVE 輸入或更新
remarks和comments欄位。 - 更新後的報告將保存為
cve_report_updated.xlsx。
4. 示例輸出
生成的 Excel 文件可能如下所示:
| 產品 | 版本 | CVE ID | 嚴重性 | 描述 | CVSS 分數 | Remarks | Comments |
|---|---|---|---|---|---|---|---|
| openssl | 1.1.1k | CVE-2021-3450 | HIGH | 漏洞描述… | 9.8 | 需要立即修復 | 影響生產環境 |
| curl | 7.64.0 | CVE-2021-22947 | MEDIUM | 漏洞描述… | 6.5 | 低風險 | 已安排修復 |
| python | 3.8.10 | CVE-2021-3177 | LOW | 漏洞描述… | 3.7 | 無需立即處理 | 僅影響測試環境 |
5. 進一步擴展
- 批量更新 :允許用戶通過 CSV 或 JSON 文件批量更新
remarks和comments。 - 歷史記錄 :為每次更新創建歷史記錄,以便追蹤更改。
- 圖形界面 :使用
tkinter或PyQt創建圖形界面,使操作更友好。
通過這種方式,你可以輕鬆維護 CVE 報告中的 remarks 和 comments 欄位,並確保報告內容始終最新。
Q4: 需要能維護并添加新掃描的 CVE項目
為了實現既能維護現有的 CVE 項目(更新 remarks 和 comments),又能添加新掃描的 CVE 項目,我們可以擴展之前的腳本。以下是實現步驟:
1. 功能需求
- 加載現有報告 :如果存在現有的 Excel 報告,加載並顯示現有的 CVE 項目。
- 添加新掃描的 CVE 項目 :從
cve-bin-tool掃描結果中添加新的 CVE 項目。 - 維護現有項目 :允許用戶更新現有項目的
remarks和comments。 - 保存更新後的報告 :將更新後的數據保存為新的 Excel 文件。
2. 安裝必要的套件
確保已安裝以下套件:
pip install openpyxl cve-bin-tool
3. 完整腳本
以下是完整的 Python 腳本,支持加載現有報告、添加新掃描的 CVE 項目,並維護現有項目:
import subprocess
import json
from openpyxl import Workbook, load_workbook
def load_existing_report(file_path):
"""
加載現有的 Excel 報告。
"""
try:
wb = load_workbook(file_path)
ws = wb.active
data = []
# 讀取數據
for row in ws.iter_rows(min_row=2, values_only=True): # 跳過表頭
data.append({
"產品": row[0],
"版本": row[1],
"CVE ID": row[2],
"嚴重性": row[3],
"描述": row[4],
"CVSS 分數": row[5],
"Remarks": row[6] if len(row) > 6 else "",
"Comments": row[7] if len(row) > 7 else ""
})
return data
except FileNotFoundError:
print("未找到現有報告,將創建新報告。")
return []
def scan_project_with_cve_bin_tool(project_path):
"""
使用 cve-bin-tool 掃描專案,並返回 JSON 格式的掃描結果。
"""
try:
# 執行 cve-bin-tool 掃描
result = subprocess.run(
["cve-bin-tool", "-q", "-f", "json", project_path],
capture_output=True,
text=True
)
if result.returncode == 0:
# 解析 JSON 輸出
return json.loads(result.stdout)
else:
print("掃描失敗:", result.stderr)
return None
except Exception as e:
print("發生錯誤:", str(e))
return None
def merge_new_cves(existing_data, new_cves):
"""
將新掃描的 CVE 項目合併到現有數據中。
"""
existing_cve_ids = {entry["CVE ID"] for entry in existing_data}
for cve in new_cves:
cve_id = cve.get("cve_number")
if cve_id not in existing_cve_ids:
existing_data.append({
"產品": cve.get("product", ""),
"版本": cve.get("version", ""),
"CVE ID": cve_id,
"嚴重性": cve.get("severity", ""),
"描述": cve.get("description", ""),
"CVSS 分數": cve.get("CVSS_version", {}).get("score", ""),
"Remarks": "",
"Comments": ""
})
print(f"已添加新 CVE: {cve_id}")
else:
print(f"CVE {cve_id} 已存在,跳過添加。")
return existing_data
def update_remarks_and_comments(data):
"""
手動更新 remarks 和 comments 欄位。
"""
for i, entry in enumerate(data):
print(f"\nCVE ID: {entry['CVE ID']}")
print(f"產品: {entry['產品']}, 版本: {entry['版本']}")
print(f"當前 Remarks: {entry.get('Remarks', '')}")
print(f"當前 Comments: {entry.get('Comments', '')}")
remarks = input("輸入新的 Remarks(留空以保持不變): ").strip()
comments = input("輸入新的 Comments(留空以保持不變): ").strip()
if remarks:
entry["Remarks"] = remarks
if comments:
entry["Comments"] = comments
return data
def save_to_excel(data, output_file="cve_report_updated.xlsx"):
"""
將更新後的數據保存為 Excel 文件。
"""
wb = Workbook()
ws = wb.active
ws.title = "CVE 報告"
# 添加表頭
headers = ["產品", "版本", "CVE ID", "嚴重性", "描述", "CVSS 分數", "Remarks", "Comments"]
ws.append(headers)
# 添加數據
for entry in data:
ws.append([
entry["產品"],
entry["版本"],
entry["CVE ID"],
entry["嚴重性"],
entry["描述"],
entry["CVSS 分數"],
entry.get("Remarks", ""),
entry.get("Comments", "")
])
# 保存文件
wb.save(output_file)
print(f"更新後的報告已保存到 {output_file}")
def main():
# 加載現有報告
report_file = input("請輸入現有報告的文件路徑(留空以創建新報告): ").strip()
if report_file:
data = load_existing_report(report_file)
else:
data = []
# 掃描專案以添加新 CVE
project_path = input("請輸入要掃描的專案路徑(留空以跳過掃描): ").strip()
if project_path:
scan_results = scan_project_with_cve_bin_tool(project_path)
if scan_results:
data = merge_new_cves(data, scan_results)
# 更新 remarks 和 comments
data = update_remarks_and_comments(data)
# 保存更新後的報告
save_to_excel(data)
if __name__ == "__main__":
main()
4. 運行腳本
- 將上述代碼保存為
cve_report_manager.py。 -
運行腳本:
bash复制
python cve_report_manager.py - 輸入現有報告的文件路徑(如果存在)。
- 輸入要掃描的專案路徑以添加新 CVE 項目(可選)。
- 腳本會提示你為每個 CVE 輸入或更新
remarks和comments欄位。 - 更新後的報告將保存為
cve_report_updated.xlsx。
5. 示例輸出
生成的 Excel 文件可能如下所示:
| 產品 | 版本 | CVE ID | 嚴重性 | 描述 | CVSS 分數 | Remarks | Comments |
|---|---|---|---|---|---|---|---|
| openssl | 1.1.1k | CVE-2021-3450 | HIGH | 漏洞描述… | 9.8 | 需要立即修復 | 影響生產環境 |
| curl | 7.64.0 | CVE-2021-22947 | MEDIUM | 漏洞描述… | 6.5 | 低風險 | 已安排修復 |
| python | 3.8.10 | CVE-2021-3177 | LOW | 漏洞描述… | 3.7 | 無需立即處理 | 僅影響測試環境 |
| libxml2 | 2.9.10 | CVE-2022-29824 | HIGH | 新掃描的漏洞描述… | 8.1 | 待評估 | 未處理 |
6. 進一步擴展
- 自動化掃描 :將此腳本與 CI/CD 工具集成,定期掃描專案並更新報告。
- 歷史記錄 :為每次更新創建歷史記錄,以便追蹤更改。
- 圖形界面 :使用
tkinter或PyQt創建圖形界面,使操作更友好。
通過這種方式,你可以輕鬆維護現有的 CVE 項目並添加新掃描的 CVE 項目,確保報告內容始終最新。
Q5: 自動掃描與建立歷史記錄
為了實現自動掃描並建立歷史記錄,我們可以擴展之前的腳本,使其支持以下功能:
- 自動掃描 :定期掃描專案並將結果添加到報告中。
- 歷史記錄 :每次掃描或更新後,保存一個帶有時間戳的歷史記錄文件。
- 合併歷史記錄 :將歷史記錄合併到主報告中,以便追蹤更改。
以下是實現步驟:
1. 功能需求
- 自動掃描 :使用
cve-bin-tool定期掃描專案。 - 歷史記錄 :每次掃描或更新後,保存一個帶有時間戳的歷史記錄文件。
- 合併歷史記錄 :將歷史記錄合併到主報告中,以便追蹤更改。
2. 安裝必要的套件
確保已安裝以下套件:
pip install openpyxl cve-bin-tool
3. 完整腳本
以下是完整的 Python 腳本,支持自動掃描、歷史記錄和合併功能:
import subprocess
import json
from openpyxl import Workbook, load_workbook
from datetime import datetime
import os
def load_existing_report(file_path):
"""
加載現有的 Excel 報告。
"""
try:
wb = load_workbook(file_path)
ws = wb.active
data = []
# 讀取數據
for row in ws.iter_rows(min_row=2, values_only=True): # 跳過表頭
data.append({
"產品": row[0],
"版本": row[1],
"CVE ID": row[2],
"嚴重性": row[3],
"描述": row[4],
"CVSS 分數": row[5],
"Remarks": row[6] if len(row) > 6 else "",
"Comments": row[7] if len(row) > 7 else "",
"Last Updated": row[8] if len(row) > 8 else ""
})
return data
except FileNotFoundError:
print("未找到現有報告,將創建新報告。")
return []
def scan_project_with_cve_bin_tool(project_path):
"""
使用 cve-bin-tool 掃描專案,並返回 JSON 格式的掃描結果。
"""
try:
# 執行 cve-bin-tool 掃描
result = subprocess.run(
["cve-bin-tool", "-q", "-f", "json", project_path],
capture_output=True,
text=True
)
if result.returncode == 0:
# 解析 JSON 輸出
return json.loads(result.stdout)
else:
print("掃描失敗:", result.stderr)
return None
except Exception as e:
print("發生錯誤:", str(e))
return None
def merge_new_cves(existing_data, new_cves):
"""
將新掃描的 CVE 項目合併到現有數據中。
"""
existing_cve_ids = {entry["CVE ID"] for entry in existing_data}
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
for cve in new_cves:
cve_id = cve.get("cve_number")
if cve_id not in existing_cve_ids:
existing_data.append({
"產品": cve.get("product", ""),
"版本": cve.get("version", ""),
"CVE ID": cve_id,
"嚴重性": cve.get("severity", ""),
"描述": cve.get("description", ""),
"CVSS 分數": cve.get("CVSS_version", {}).get("score", ""),
"Remarks": "",
"Comments": "",
"Last Updated": current_time
})
print(f"已添加新 CVE: {cve_id}")
else:
# 更新現有項目的最後更新時間
for entry in existing_data:
if entry["CVE ID"] == cve_id:
entry["Last Updated"] = current_time
print(f"已更新 CVE {cve_id} 的最後更新時間。")
return existing_data
def update_remarks_and_comments(data):
"""
手動更新 remarks 和 comments 欄位。
"""
for i, entry in enumerate(data):
print(f"\nCVE ID: {entry['CVE ID']}")
print(f"產品: {entry['產品']}, 版本: {entry['版本']}")
print(f"當前 Remarks: {entry.get('Remarks', '')}")
print(f"當前 Comments: {entry.get('Comments', '')}")
remarks = input("輸入新的 Remarks(留空以保持不變): ").strip()
comments = input("輸入新的 Comments(留空以保持不變): ").strip()
if remarks:
entry["Remarks"] = remarks
if comments:
entry["Comments"] = comments
return data
def save_to_excel(data, output_file="cve_report_updated.xlsx"):
"""
將更新後的數據保存為 Excel 文件。
"""
wb = Workbook()
ws = wb.active
ws.title = "CVE 報告"
# 添加表頭
headers = ["產品", "版本", "CVE ID", "嚴重性", "描述", "CVSS 分數", "Remarks", "Comments", "Last Updated"]
ws.append(headers)
# 添加數據
for entry in data:
ws.append([
entry["產品"],
entry["版本"],
entry["CVE ID"],
entry["嚴重性"],
entry["描述"],
entry["CVSS 分數"],
entry.get("Remarks", ""),
entry.get("Comments", ""),
entry.get("Last Updated", "")
])
# 保存文件
wb.save(output_file)
print(f"更新後的報告已保存到 {output_file}")
def save_history(data, history_dir="history"):
"""
保存歷史記錄。
"""
if not os.path.exists(history_dir):
os.makedirs(history_dir)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
history_file = os.path.join(history_dir, f"cve_history_{timestamp}.json")
with open(history_file, "w") as file:
json.dump(data, file, indent=4)
print(f"歷史記錄已保存到 {history_file}")
def main():
# 加載現有報告
report_file = input("請輸入現有報告的文件路徑(留空以創建新報告): ").strip()
if report_file:
data = load_existing_report(report_file)
else:
data = []
# 掃描專案以添加新 CVE
project_path = input("請輸入要掃描的專案路徑(留空以跳過掃描): ").strip()
if project_path:
scan_results = scan_project_with_cve_bin_tool(project_path)
if scan_results:
data = merge_new_cves(data, scan_results)
# 更新 remarks 和 comments
data = update_remarks_and_comments(data)
# 保存更新後的報告
save_to_excel(data)
# 保存歷史記錄
save_history(data)
if __name__ == "__main__":
main()
4. 運行腳本
- 將上述代碼保存為
cve_report_manager.py。 -
運行腳本:
bash复制
python cve_report_manager.py - 輸入現有報告的文件路徑(如果存在)。
- 輸入要掃描的專案路徑以添加新 CVE 項目(可選)。
- 腳本會提示你為每個 CVE 輸入或更新
remarks和comments欄位。 - 更新後的報告將保存為
cve_report_updated.xlsx,並在history目錄下保存歷史記錄。
5. 示例輸出
主報告 (cve_report_updated.xlsx)
| 產品 | 版本 | CVE ID | 嚴重性 | 描述 | CVSS 分數 | Remarks | Comments | Last Updated |
|---|---|---|---|---|---|---|---|---|
| openssl | 1.1.1k | CVE-2021-3450 | HIGH | 漏洞描述… | 9.8 | 需要立即修復 | 影響生產環境 | 2023-10-01 12:34:56 |
| curl | 7.64.0 | CVE-2021-22947 | MEDIUM | 漏洞描述… | 6.5 | 低風險 | 已安排修復 | 2023-10-01 12:34:56 |
| python | 3.8.10 | CVE-2021-3177 | LOW | 漏洞描述… | 3.7 | 無需立即處理 | 僅影響測試環境 | 2023-10-01 12:34:56 |
歷史記錄 (history/cve_history_20231001_123456.json)
[
{
"產品": "openssl",
"版本": "1.1.1k",
"CVE ID": "CVE-2021-3450",
"嚴重性": "HIGH",
"描述": "漏洞描述...",
"CVSS 分數": "9.8",
"Remarks": "需要立即修復",
"Comments": "影響生產環境",
"Last Updated": "2023-10-01 12:34:56"
},
{
"產品": "curl",
"版本": "7.64.0",
"CVE ID": "CVE-2021-22947",
"嚴重性": "MEDIUM",
"描述": "漏洞描述...",
"CVSS 分數": "6.5",
"Remarks": "低風險",
"Comments": "已安排修復",
"Last Updated": "2023-10-01 12:34:56"
}
]
6. 進一步擴展
- 自動化定期掃描 :使用
cron(Linux)或Task Scheduler(Windows)定期運行腳本。 - 郵件通知 :在掃描完成後,通過電子郵件發送報告。
- 圖形界面 :使用
tkinter或PyQt創建圖形界面,使操作更友好。
通過這種方式,你可以實現自動掃描、維護歷史記錄,並確保 CVE 報告內容始終最新。
Q6: Linux下自動化定期掃描
在 Linux 系統中,可以使用 cron 來實現自動化定期掃描。cron 是一個用於定期執行任務的調度工具。以下是實現步驟:
1. 準備 Python 腳本
確保你已經有一個用於掃描和生成 CVE 報告的 Python 腳本(例如 cve_report_manager.py)。如果還沒有,可以使用以下簡化版腳本:
import subprocess
import json
from datetime import datetime
def scan_project_with_cve_bin_tool(project_path):
"""
使用 cve-bin-tool 掃描專案,並返回 JSON 格式的掃描結果。
"""
try:
result = subprocess.run(
["cve-bin-tool", "-q", "-f", "json", project_path],
capture_output=True,
text=True
)
if result.returncode == 0:
return json.loads(result.stdout)
else:
print("掃描失敗:", result.stderr)
return None
except Exception as e:
print("發生錯誤:", str(e))
return None
def save_report(data, output_dir="reports"):
"""
將掃描結果保存為 JSON 文件。
"""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
report_file = os.path.join(output_dir, f"cve_report_{timestamp}.json")
with open(report_file, "w") as file:
json.dump(data, file, indent=4)
print(f"報告已保存到 {report_file}")
def main():
project_path = "/path/to/your/project" # 替換為你的專案路徑
scan_results = scan_project_with_cve_bin_tool(project_path)
if scan_results:
save_report(scan_results)
if __name__ == "__main__":
main()
將上述腳本保存為 cve_report_manager.py,並確保它可以在命令行中運行。
2. 設置 cron 任務
步驟 1:編輯 crontab
在終端中運行以下命令來編輯當前用戶的 cron 任務:
crontab -e
步驟 2:添加定期掃描任務
在打開的 crontab 文件中,添加一行來定義定期掃描任務。例如:
# 每天凌晨 2 點運行掃描腳本
0 2 * * * /usr/bin/python3 /path/to/cve_report_manager.py >> /path/to/cve_scan.log 2>&1
0 2 * * *:表示每天凌晨 2 點運行。/usr/bin/python3:Python 解釋器的路徑(可以使用which python3來確認路徑)。/path/to/cve_report_manager.py:你的 Python 腳本的路徑。>> /path/to/cve_scan.log 2>&1:將腳本的輸出和錯誤信息重定向到日誌文件。
步驟 3:保存並退出
保存 crontab 文件並退出編輯器。cron 會自動加載新的任務。
3. 檢查 cron 任務
查看當前 cron 任務
運行以下命令查看當前用戶的 cron 任務:
crontab -l
檢查日誌
定期檢查日誌文件 /path/to/cve_scan.log,確認腳本是否按預期運行。
4. 進一步優化
自動化報告合併
如果每次掃描都生成一個新的報告文件,可以編寫一個腳本將所有報告合併為一個主報告。例如:
import os
import json
def merge_reports(report_dir="reports", output_file="merged_cve_report.json"):
merged_data = []
for filename in os.listdir(report_dir):
if filename.endswith(".json"):
with open(os.path.join(report_dir, filename), "r") as file:
data = json.load(file)
merged_data.extend(data)
with open(output_file, "w") as file:
json.dump(merged_data, file, indent=4)
print(f"合併後的報告已保存到 {output_file}")
if __name__ == "__main__":
merge_reports()
將此腳本添加到 cron 任務中,定期合併報告。
郵件通知
在掃描完成後,可以使用 sendmail 或 mail 命令發送郵件通知。例如:
0 2 * * * /usr/bin/python3 /path/to/cve_report_manager.py >> /path/to/cve_scan.log 2>&1 && mail -s "CVE 掃描完成" your-email@example.com < /path/to/cve_scan.log
5. 示例 cron 任務
以下是一個完整的 cron 任務示例:
# 每天凌晨 2 點運行掃描腳本
0 2 * * * /usr/bin/python3 /path/to/cve_report_manager.py >> /path/to/cve_scan.log 2>&1
# 每週日凌晨 3 點合併報告
0 3 * * 0 /usr/bin/python3 /path/to/merge_reports.py >> /path/to/merge_reports.log 2>&1
# 掃描完成後發送郵件通知
0 2 * * * /usr/bin/python3 /path/to/cve_report_manager.py >> /path/to/cve_scan.log 2>&1 && mail -s "CVE 掃描完成" your-email@example.com < /path/to/cve_scan.log
通過以上步驟,你可以在 Linux 系統中實現自動化定期掃描,並生成 CVE 報告。
留言