網路自動化在現今網路環境中扮演著至關重要的角色,有效降低人力成本並提升管理效率。本文提供的 Python 網路自動化工具,整合了 Netmiko 和 Nornir 等主流函式庫,實作了裝置組態、檔案傳輸、伺服器管理、日誌收集與郵件通知等核心功能。藉由模組化設計,主程式能清晰地劃分不同任務,並透過設定檔集中管理裝置資訊,簡化操作流程。此外,多執行緒技術的應用,更大幅提升了日誌收集的效率,並能根據 CPU 使用率等指標進行風險評估,及時發現潛在問題。
網路自動化工具的主程式架構與實作
在網路自動化領域中,開發一個整合多種功能的工具對於提升維運效率至關重要。本文將探討如何設計並實作一個具備多項功能的網路自動化工具,包括裝置組態、檔案傳輸、伺服器組態以及其他輔助功能。
主程式的設計與功能選項
主程式採用模組化設計,將不同功能劃分為獨立的模組,並透過主選單進行選擇和執行。主選單提供以下主要功能選項:
- 裝置組態(Device Configuration):允許使用者透過Netmiko或Nornir進行裝置組態。
- 檔案傳輸(File Transfer):支援使用SCP或SFTP進行檔案的上傳。
- 伺服器組態(Server Configuration):提供多項伺服器組態和資訊收集功能。
- 其他功能(Others):包含子網計算器、Ping測試、CPU使用率繪圖以及介面頻寬繪圖等輔助工具。
裝置組態功能的實作
裝置組態功能允許使用者選擇使用Netmiko或Nornir進行裝置組態。在選擇具體的組態方法後,程式會要求使用者確認裝置清單和命令清單檔案。
elif main_task == "Device Configuration":
sub_task = inquirer.select(
message="Choose a Sub Task:",
choices=["Configure With Netmiko", "Configure With Nornir", "Exit"]).execute()
if sub_task == "Configure With Netmiko":
result = inquirer.confirm(message="\n**IP addresses in 'input/device_list.txt'\n**Commands in 'input/command_list.txt'\n").execute()
if result:
configure_device.config_with_netmiko()
else:
print("Exited from the tool.")
檔案傳輸功能的實作
檔案傳輸功能支援SCP和SFTP兩種協定,使用者需指定來源檔案和目標檔案的名稱。
elif main_task == "File Transfer":
sub_task = inquirer.select(
message="Choose a Sub Task:",
choices=["Upload with SCP to Routers", "Upload with SFTP to Servers", "Exit"]).execute()
if sub_task == "Upload with SCP to Routers":
src_file = inquirer.text(message="Source File on PC:").execute()
dest_file = inquirer.text(message="Destination File:").execute()
transfer_files.scp_upload_to_routers(src_file, dest_file)
伺服器組態功能的實作
伺服器組態功能提供多項子功能,包括組態或收集資訊、收集資源使用情況、收集介面資訊以及安裝套件。
elif main_task == "Server Configuration":
sub_task = inquirer.select(
message="Choose a Sub Task:",
choices=["Configure or Collect Info", "Collect Resource Usage", "Collect Interface Information ", "Install Packages", "Exit"]).execute()
if sub_task == "Configure or Collect Info":
result = inquirer.confirm(message="\n**IP addresses in 'input/device_list.txt'\n**Commands in 'input/command_list.txt'\n").execute()
if result:
config_and_collect_logs.config_collect_logs()
else:
print("Exited from the tool.")
其他功能的實作
其他功能模組提供多項輔助工具,如子網計算器和Ping測試等。
elif main_task == "Others":
sub_task = inquirer.select(
message="Choose a Sub Task:",
choices=["Subnet Calculator", "Ping Test", "Plotting CPU Levels", "Plotting Interface Bandwidth", "Exit"]).execute()
if sub_task == "Subnet Calculator":
ip_address = inquirer.text(message="Enter an IP address:").execute()
subnet_mask = inquirer.text(message="Enter a Subnet Mask (1 to 32): ").execute()
tools.subnet_calculator(ip_address, subnet_mask)
設定檔與裝置資訊管理
裝置資訊可以透過device_list.txt和hosts.yaml檔案進行管理。device_list.txt檔案儲存裝置的IP地址,而hosts.yaml檔案則包含裝置的詳細連線資訊,包括主機名、平台、使用者名稱和密碼。
device_list.txt 範例
10.10.10.1
10.10.10.2
10.10.10.3
hosts.yaml 範例
Router-1:
hostname: 10.10.10.1
platform: ios
username: admin
password: cisco
Router-2:
hostname: 10.10.10.2
platform: ios
username: admin
password: cisco
Router-3:
hostname: 10.10.10.3
platform: ios
username: admin
password: cisco
子任務指令碼的建立
子任務指令碼,如network_devices.py,用於實作具體的裝置操作功能。這些指令碼透過匯入必要的模組並定義相關的類別和函式來完成特定的任務。
from netmiko import Netmiko
from concurrent.futures import ThreadPoolExecutor
from re import findall, split
from pandas import DataFrame
import smtplib
from email import message
import mimetypes
from nornir import InitNornir
from nornir_utils.plugins.functions import print_result
from nornir_netmiko import netmiko_send_config, netmiko_file_transfer
from paramiko import SSHClient, AutoAddPolicy
class collect_logs:
def from_one_device(self, device_ip, command):
# 登入單一裝置,收集單一命令日誌,並顯示輸出
pass # 程式碼實作細節省略
補充說明
為了進一步增強工具的功能性和可用性,可以考慮新增更多的功能模組,例如網路拓撲發現、安全稽核等。同時,改善使用者介面和體驗也是未來發展的重要方向。透過不斷最佳化和擴充套件,該網路自動化工具將能夠在網路維運領域發揮更大的作用。
內容解密:
上述程式碼與解說涵蓋了網路自動化工具的主要架構和實作細節。透過將不同功能模組化,並採用靈活的設定檔管理方式,該工具具備了良好的擴充套件性和適應性。未來,可以根據實際需求對工具進行進一步的最佳化和擴充套件,以提升其在網路維運領域的應用價值。
值得注意的是,在實際佈署和使用該工具時,應確保相關設定檔的安全性,避免敏感資訊(如裝置登入憑證)的洩露。同時,定期更新和維護工具的功能和效能,也是確保其長期有效執行的關鍵。
最後,透過不斷地實踐和改進,該網路自動化工具將能夠更好地服務於網路維運工作,為提升網路管理的效率和安全性做出更大的貢獻。
網路裝置資訊收集與日誌管理的自動化實作
在現代網路管理中,自動化收集網路裝置的日誌和資訊對於維護網路穩定性和安全性至關重要。本文將介紹如何使用Python和Netmiko模組實作網路裝置資訊的收集、日誌管理和郵件通知等功能。
從單一裝置收集日誌資訊
首先,我們來看看如何從單一裝置收集日誌資訊。以下是一個簡單的函式範例:
def from_one_device(ip, username, password, command):
device = {"host": ip, "username": username, "password": password, "device_type": "cisco_ios"}
net_connect = Netmiko(**device)
show_output = net_connect.send_command(command)
print(show_output)
內容解密:
- 函式定義:
from_one_device函式接受四個引數:裝置IP、使用者名稱、密碼和要執行的命令。 - 裝置連線設定:使用字典
device儲存連線裝置所需的資訊,包括主機IP、使用者名稱、密碼和裝置型別(此例中為Cisco IOS裝置)。 - Netmiko連線:透過
Netmiko(**device)建立與裝置的連線。 - 傳送命令:使用
send_command方法向裝置傳送指定的命令,並將輸出結果儲存在show_output變數中。 - 輸出結果:列印出命令的執行結果。
從多台裝置收集日誌資訊
在實際環境中,我們通常需要從多台裝置收集日誌。以下範例展示瞭如何使用多執行緒技術從多台裝置平行收集日誌:
def from_multiple_devices():
with open("input/device_list.txt") as r:
device_list = r.read().splitlines()
with open("input/command_list.txt") as r:
command_list = r.read().splitlines()
def concurrent(ip):
device = {"host": ip, "username": "admin", "password": "cisco", "device_type": "cisco_ios"}
net_connect = Netmiko(**device)
hostname = net_connect.find_prompt()
for command in command_list:
output = net_connect.send_command(command, strip_command=False)
print(f"{hostname} {output}\n")
with open(f"output/{ip} logs.txt", "a") as w:
w.write(f"{hostname} {output}\n\n")
with ThreadPoolExecutor(max_workers=25) as executor:
executor.map(concurrent, device_list)
內容解密:
- 讀取裝置清單和命令清單:從指定的文字檔中讀取裝置IP清單和要執行的命令清單。
- 平行處理函式:定義了一個名為
concurrent的內部函式,用於處理單一裝置的連線和命令執行。 - 多執行緒執行:使用
ThreadPoolExecutor實作多執行緒平行處理,大幅提高從多台裝置收集日誌的效率。 - 結果儲存:將每台裝置的命令輸出結果儲存到以其IP命名的日誌檔案中。
收集網路裝置資訊
除了日誌收集,我們還可以自動化收集網路裝置的詳細資訊,如IP位址、主機名稱、供應商型別、裝置型號和軟體版本等:
def collect_device_info():
with open("input/device_list.txt") as r:
device_list = r.read().splitlines()
ip_list, version_list, model_list, vendor_list, hostname_list = ([] for i in range(5))
for ip in device_list:
device = {"host": ip, "username": "admin", "password": "cisco", "device_type": "cisco_ios"}
print(f"\n
---
Try to Login:{ip}
---
\n")
net_connect = Netmiko(**device)
output = net_connect.send_command("show version")
version = findall("Version (.*),", output)
model = findall("Cisco (.*)\(revision", output)
vendor = findall("Cisco", output)
hostname = findall("(.*)#", net_connect.find_prompt())
ip_list.append(ip)
version_list.append(version[0])
model_list.append(model[0])
vendor_list.append(vendor[0])
hostname_list.append(hostname[0])
df = DataFrame({"IP Address": ip_list, "Hostname": hostname_list, "Vendor Type": vendor_list, "Model": model_list, "Version": version_list})
df.to_excel("output/Version List.xlsx", sheet_name="Vendors", index=False)
內容解密:
- 初始化清單:為儲存不同型別資訊的清單進行初始化。
- 遍歷裝置清單:對每個裝置執行連線並擷取所需資訊。
- 解析命令輸出:使用正規表示式從
show version命令的輸出中擷取版本、型號、供應商等資訊。 - 資料儲存:將收集到的資訊儲存到DataFrame中,並匯出為Excel檔案。
收集CPU使用率資訊
同樣地,我們也可以收集網路裝置的CPU使用率資訊,並根據使用率評估風險級別:
def collect_cpu_usage():
with open("input/device_list.txt") as r:
device_list = r.read().splitlines()
ip_list, cpu_list_5s, cpu_list_1m, cpu_list_5m, cpu_list_risk = ([] for x in range(5))
for ip in device_list:
device = {"host": ip, "username": "admin", "password": "cisco", "device_type": "cisco_ios"}
print(f"\n
---
Try to Login:{ip}
---
\n")
net_connect = Netmiko(**device)
output = net_connect.send_command("show processes cpu")
cpu_5s = findall("CPU utilization for five seconds: (\d+)", output)
cpu_1m = findall("one minute: (\d+)", output)
cpu_5m = findall("five minutes: (\d+)", output)
ip_list.append(ip)
cpu_list_5s.append(cpu_5s[0] + "%")
cpu_list_1m.append(cpu_1m[0] + "%")
cpu_list_5m.append(cpu_5m[0] + "%")
if int(cpu_5m[0]) > 90:
cpu_risk = "Fatal CPU Level"
elif 70 < int(cpu_5m[0]) < 90:
cpu_risk = "High CPU Level"
else:
cpu_risk = "No Risk"
cpu_list_risk.append(cpu_risk)
df = DataFrame({"IP Address": ip_list, "CPU Levels for 5 Seconds": cpu_list_5s, "CPU Levels for 1 Minute": cpu_list_1m, "CPU Levels for 5 Minutes": cpu_list_5m, "CPU Risk": cpu_list_risk})
df.to_excel("output/CPU Levels.xlsx", index=False)
內容解密:
- 初始化清單:為儲存CPU使用率相關資訊的清單進行初始化。
- 遍歷裝置清單:對每個裝置執行連線並擷取CPU使用率資訊。
- 風險評估:根據5分鐘內的CPU平均使用率評估風險級別。
- 資料儲存:將收集到的CPU使用率資訊和風險評估結果儲存到DataFrame中,並匯出為Excel檔案。
將收集的日誌透過電子郵件傳送
最後,我們可以將收集到的日誌檔案透過電子郵件傳送給相關人員:
def send_logs_by_email():
# 省略部分程式碼...
with ThreadPoolExecutor(max_workers=25) as executor:
executor.map(concurrent, device_list)
print("\nSending Email")
# 設定電子郵件相關資訊並傳送...
內容解密:
- 多執行緒收集日誌:使用多執行緒技術平行收集多台裝置的日誌。
- 電子郵件設定:設定電子郵件的傳送者、收件者、主題和內容。
- 附件新增:將收集的日誌檔案作為附件新增到電子郵件中。
- 傳送電子郵件:傳送包含日誌附件的電子郵件。
這些範例展示瞭如何使用Python和Netmiko模組自動化網路裝置的日誌收集、資訊管理和郵件通知等任務,大大提高了網路管理的效率和準確性。