網路自動化已成為現代網路管理的關鍵技術。本文將探討如何利用 Python 結合 Netmiko、Nornir 和 Matplotlib 等模組,實作 SCP 檔案傳輸、組態備份和網路裝置效能資料視覺化。藉由 ThreadPoolExecutor,我們可以有效提升檔案傳輸效率,而 Nornir 框架則簡化了多裝置管理的複雜性。此外,Matplotlib 的整合讓網路工程師能以圖表方式呈現裝置資料,例如 CPU 使用率,進而更直觀地監控網路效能並快速做出應對。
使用ThreadPoolExecutor實作平行SCP檔案傳輸
在預設情況下,使用ThreadPoolExecutor的程式碼只能同時登入12台裝置,但我們可以透過max_workers引數來更改這個預設值。在這個例子中,我們將max_workers設為25,但實際上這個值可以根據本地電腦的資源進行調整。當我們執行程式碼時,本地電腦的CPU和記憶體資源會被佔用。我們也可以將max_workers的值設為1,以觀察不同max_workers值下的時間差異。
程式碼範例
from concurrent.futures import ThreadPoolExecutor
from netmiko import Netmiko, file_transfer, progress_bar
def get_ip_address():
with open("device_list.txt") as r:
host_list = r.read().splitlines()
return host_list
def netmiko_scp(ip):
host = {"ip": ip, "username": "admin", "password": "cisco", "device_type": "cisco_ios"}
print(f"
---
嘗試登入:{ip}
---
")
net_connect = Netmiko(**host)
file_transfer(net_connect, source_file="test.txt", dest_file="test.txt", direction="put", file_system="flash:", overwrite_file=True, progress4=progress_bar)
net_connect.disconnect()
return
with ThreadPoolExecutor(max_workers=25) as executor:
host_ip = get_ip_address()
result = executor.map(netmiko_scp, host_ip)
內容解密:
ThreadPoolExecutor的使用:透過設定max_workers=25,我們可以同時對多台裝置進行SCP檔案傳輸,大大提高了效率。netmiko_scp函式:定義瞭如何對單一裝置進行SCP檔案傳輸的過程,包括建立Netmiko連線、檔案傳輸以及斷開連線。get_ip_address函式:從device_list.txt檔案中讀取裝置IP列表,為後續的平行處理做準備。file_transfer函式:使用Netmiko的file_transfer功能,將本地檔案傳輸到遠端裝置,並顯示傳輸進度。
Nornir框架下的SCP檔案傳輸
除了使用ThreadPoolExecutor之外,我們也可以利用Nornir框架來實作SCP檔案傳輸。Nornir內建了平行處理的能力,使得同時連線多台裝置變得更加簡單。
程式碼範例
from nornir import InitNornir
from nornir_utils.plugins.functions import print_result
from nornir_netmiko import netmiko_file_transfer
connect = InitNornir()
result = connect.run(task=netmiko_file_transfer, source_file="test.txt", dest_file="test.txt")
print_result(result)
內容解密:
- 初始化Nornir:透過
InitNornir()初始化Nornir框架,並自動讀取hosts.yaml中的裝置資訊。 - 執行檔案傳輸任務:使用
connect.run()方法執行netmiko_file_transfer任務,將檔案從本地傳輸到遠端裝置。 - 列印結果:透過
print_result()函式輸出任務執行的結果,確認檔案傳輸是否成功。
網路裝置管理:檔案傳輸與組態備份
在網路管理中,檔案傳輸與組態備份是至關重要的任務。Netmiko 和 Nornir-Netmiko 模組提供了強大的工具來實作這些功能。
使用 Nornir-Netmiko 進行檔案傳輸
Nornir-Netmiko 模組簡化了網路裝置之間的檔案傳輸過程。以下是一個使用 netmiko_file_transfer 任務的範例:
result = connect.run(task=netmiko_file_transfer,
source_file="test2.txt",
dest_file="test2.txt",
direction="get")
在這個範例中,我們使用 netmiko_file_transfer 任務從遠端裝置下載檔案到本地 PC。direction 引數設為 "get",表示從遠端裝置取得檔案。
內容解密:
netmiko_file_transfer是 Nornir-Netmiko 模組中的一個任務,用於在網路裝置之間傳輸檔案。source_file和dest_file引數分別指定了源檔案和目標檔案的名稱。direction引數決定了檔案傳輸的方向,可以是"put"(上傳)或"get"(下載)。
使用 Netmiko 進行組態備份
Netmiko 提供了 file_transfer 函式來實作檔案傳輸。以下是一個使用 Netmiko 備份 Cisco 路由器組態的範例:
from netmiko import Netmiko, file_transfer
import json
from datetime import datetime
def json_device():
host_list = []
with open('device_list.json') as json_file:
data = json.load(json_file)
for item in data.items():
host = item[1][0]
host_list.append(host)
return host_list
host = json_device()
for ip in host:
net_connect = Netmiko(**ip)
print(f"\n
---
-Try to login: {ip['host']}
---
\n")
save = net_connect.send_command("wr")
print(save)
time = datetime.now().strftime("%Y_%m_%d_%H_%M_%S")
hostname = net_connect.find_prompt()[:-1]
file_transfer(net_connect,
source_file="startup-config",
dest_file=f"{hostname} backup_config {time}.cfg",
direction="get",
file_system="nvram:",
overwrite_file=True)
net_connect.disconnect()
內容解密:
- 首先,我們定義了一個
json_device函式來讀取 JSON 檔案中的裝置資訊。 - 然後,我們遍歷裝置列表,使用 Netmiko 連線到每個裝置,並執行
wr命令來儲存組態。 - 使用
datetime模組取得當前時間,並將其格式化為字串。 - 使用
find_prompt函式取得裝置的主機名。 - 使用
file_transfer函式下載裝置的startup-config檔案到本地 PC,並將其儲存為帶有時間戳的檔案。 - 最後,斷開與裝置的連線。
利用Python的Matplotlib模組繪製圖形
在網路自動化領域中,圖形的使用十分普遍。我們可以建立各種圖表,如折線圖、散點圖或柱狀圖,以直觀地展示網路裝置的資料。網路監控系統(NMS)工具可以從網路裝置中收集資料,並將其繪製成圖形,例如介面頻寬、CPU和記憶體使用率等,以便我們及時採取相應的措施。
繪製圖形的基本步驟
要使用Python繪製圖形,我們需要安裝matplotlib模組。安裝完成後,我們可以匯入pyplot函式,並使用其提供的各種功能來建立圖形。
import matplotlib.pyplot as plt
內容解密:
import matplotlib.pyplot as plt:匯入matplotlib模組中的pyplot函式,並將其命名為plt,以便在後續程式碼中使用。
建立簡單的折線圖
下面是一個簡單的例子,展示如何使用matplotlib建立一個折線圖。
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
plt.plot(a, b)
plt.show()
內容解密:
a = [1, 2, 3, 4, 5]和b = [10, 20, 30, 40, 50]:建立兩個列表,分別代表X軸和Y軸的資料。plt.plot(a, b):使用plot函式建立折線圖,a和b分別代表X軸和Y軸的資料。plt.show():顯示繪製好的圖形。
自定義圖形
我們可以透過新增標題、標籤和網格等方式來自定義圖形,使其更具可讀性。
import matplotlib.pyplot as plt
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
plt.figure(figsize=(8, 8), facecolor='#FFFFFF')
plt.plot(a, b, color='red')
plt.xlabel('Time in Seconds')
plt.ylabel('CPU Levels')
plt.title('CPU Level Measure Drawing')
plt.grid(True)
plt.show()
內容解密:
plt.figure(figsize=(8, 8), facecolor='#FFFFFF'):設定圖形的大小和背景顏色。plt.plot(a, b, color='red'):建立折線圖,並將線條顏色設定為紅色。plt.xlabel('Time in Seconds')和plt.ylabel('CPU Levels'):為X軸和Y軸新增標籤。plt.title('CPU Level Measure Drawing'):為圖形新增標題。plt.grid(True):在圖形中新增網格。
常用的Pyplot函式
plot(X, Y):建立折線圖,X和Y分別代表X軸和Y軸的資料。xlabel():為X軸新增標籤。ylabel():為Y軸新增標籤。title():為圖形新增標題。show():顯示繪製好的圖形。figure():設定圖形的大小和背景顏色等屬性。
透過使用這些函式,我們可以建立出各種各樣的圖形,以滿足不同的需求。
使用 Matplotlib 進行資料視覺化
Matplotlib 是 Python 中一個強大的資料視覺化工具,能夠建立各種形式的圖表,如線圖、散點圖、柱狀圖等。在本章中,我們將探討如何使用 Matplotlib 進行資料視覺化,並透過實際例子來展示其強大的功能。
基本繪圖功能
首先,我們來看看如何使用 Matplotlib 繪製一個簡單的線圖。下面的程式碼演示瞭如何建立一個線圖,並對其進行自定義。
import matplotlib.pyplot as plt
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
plt.figure(figsize=(8, 8), facecolor="#FFCEB4")
plt.plot(a, b, color="Red")
plt.xlabel("Value of 'a'")
plt.ylabel("Value of 'b'")
plt.title("Chart of 'a' and 'b' Values")
plt.grid(True)
plt.show()
內容解密:
import matplotlib.pyplot as plt:匯入 Matplotlib 的 pyplot 模組,並賦予別名plt以便於使用。a和b:定義兩個列表,分別代表 X 軸和 Y 軸的資料。plt.figure(figsize=(8, 8), facecolor="#FFCEB4"):建立一個新的圖形視窗,設定其大小為 8x8 英寸,背景顏色為#FFCEB4。plt.plot(a, b, color="Red"):繪製a和b的線圖,線條顏色為紅色。plt.xlabel、plt.ylabel和plt.title:分別設定 X 軸標籤、Y 軸標籤和圖表標題。plt.grid(True):啟用網格顯示,使圖表更易於閱讀。plt.show():顯示圖表。
自定義繪圖
Matplotlib 提供了多種方式來自定義圖表。例如,我們可以透過替換 plot 函式為 scatter 函式來建立散點圖。
plt.scatter(a, b, color="Red")
內容解密:
plt.scatter(a, b, color="Red"):建立a和b的散點圖,點的顏色為紅色。
此外,Matplotlib 還支援其他型別的圖表,如柱狀圖(bar)、莖葉圖(stem)、階梯圖(step)和填充區域圖(fill_between)等。
多重繪圖
我們可以在同一個視窗中繪製多個圖表。下面是一個例子,展示瞭如何在同一個視窗中繪製兩條不同的線。
import matplotlib.pyplot as plt
a = [1, 2, 3, 4, 5]
b = [10, 20, 30, 40, 50]
c = [6, 8, 10, 12, 14]
d = [30, 50, 23, 64, 72]
plt.plot(a, b, color="Red")
plt.plot(c, d, color="Blue")
plt.show()
內容解密:
plt.plot(a, b, color="Red")和plt.plot(c, d, color="Blue"):分別繪製兩條線,顏色分別為紅色和藍色。
繪製 CPU 使用率
在下面的例子中,我們將展示如何使用 Matplotlib 繪製 Cisco 裝置的 CPU 使用率。
from matplotlib import pyplot as plt
import re
from netmiko import Netmiko
from time import sleep
from datetime import datetime
# 設定裝置連線資訊
host = {"host": "10.10.10.1", "username": "admin", "password": "cisco", "device_type": "cisco_ios", "global_delay_factor": 0.1}
count = 7
delay = 3
command = "show processes cpu"
cpu_levels = []
time_list = []
# 連線裝置並收集 CPU 使用率資料
net_connect = Netmiko(**host)
for i in range(1, count):
output = net_connect.send_command(command)
time = datetime.now().strftime("%H:%M:%S")
time_list.append(time)
sleep(delay)
cpu_data = re.findall("CPU utilization for five seconds: (\d+)%/", output)
cpu_levels.append(int(cpu_data[0]))
# 繪製 CPU 使用率圖表
plt.plot(time_list, cpu_levels)
plt.xlabel("Time")
plt.ylabel("CPU Levels in %")
plt.grid(True)
plt.show()
內容解密:
- 使用 Netmiko 連線 Cisco 裝置,並執行
show processes cpu命令來收集 CPU 使用率。 - 使用正規表示式提取 CPU 使用率資料,並將其儲存在
cpu_levels列表中。 - 使用
time_list儲存每次收集資料的時間戳。 - 繪製 CPU 使用率圖表,X 軸表示時間,Y 軸表示 CPU 使用率。