Netmiko 模組簡化了與 Linux 伺服器的互動,提供比 Paramiko 更便捷的操作方式。透過 Netmiko,我們可以輕鬆地執行指令、收集系統資訊,並將結果儲存或進一步處理。此方法適用於需要定期監控伺服器狀態或執行特定任務的場景,有助於提升網路管理效率。

使用 Netmiko 連線 Linux 伺服器並執行指令

from netmiko import Netmiko
from getpass import getpass

host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
password = getpass()
command = "uname -a"

for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": password, "device_type": "linux"}
    net_connect = Netmiko(**device)
    show_output = net_connect.send_command(command)
    net_connect.disconnect()
    print(f"{ip}:{show_output}\n")

收集 Syslog 日誌並過濾 SSH 相關資訊

from netmiko import Netmiko
from getpass import getpass

host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
password = getpass()

for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": password, "device_type": "linux"}
    command = "cat /var/log/syslog | grep 'SSH\|ssh'"
    net_connect = Netmiko(**device)
    output = net_connect.send_command(command)
    net_connect.disconnect()
    with open(f"{ip}_ssh_syslog.txt", "a") as w:
        w.write(output)

收集 CPU 和記憶體使用率,並儲存至 Excel 檔案

from netmiko import Netmiko
from re import findall
from pandas import DataFrame
from getpass import getpass

memory_total, memory_free, memory_used, cpu_used, host_list = ([] for i in range(5))
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
password = getpass()

for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": password, "device_type": "linux"}
    net_connect = Netmiko(**device)
    mem_output = net_connect.send_command("free -m", strip_command=False)
    cpu_output = net_connect.send_command("top -n 1 | grep %Cpu", strip_command=False)
    hostname = findall("@(.*):", net_connect.find_prompt())
    total = findall("Mem:\s+(\d+)", mem_output)
    free = findall("Mem:\s+\d+\s+(\d+)", mem_output)
    used = findall("Mem:\s+\d+\s+\d+\s+(\d+)", mem_output)
    cpu = findall("\d+,\d+", cpu_output)
    memory_total.append(f"{total[0]} MB")
    memory_free.append(f"{free[0]} MB")
    memory_used.append(f"{used[0]} MB")
    cpu_used.append(f"% {cpu[0]}")
    host_list.append(hostname[0])
    net_connect.disconnect()

df = DataFrame({"Hostname": host_list, "Total Memory": memory_total, "Free Memory": memory_free, "Memory Usage": memory_used, "CPU Usage": cpu_used})
df.to_excel("CPU-Memory Usage.xlsx", index=False)

收集網路介面資訊

from netmiko import Netmiko
from re import findall
from pandas import DataFrame
from getpass import getpass

list_ipv4, list_netmask, list_int, list_hostname, list_int_name = ([] for i in range(5))
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
password = getpass()

for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": password, "device_type": "linux"}
    net_connect = Netmiko(**device)
    output = net_connect.send_command("ifconfig")
    hostname = findall("@(.*):", net_connect.find_prompt())
    int_name = findall("^(.*?): flags", output, re.M)
    ipv4 = findall("inet (.*?)  netmask", output, re.M)
    netmask = findall("netmask (.*?)  broadcast", output, re.M)
    list_ipv4.extend(ipv4)
    list_netmask.extend(netmask)
    list_int.extend([ip] * len(ipv4))
    list_hostname.extend([hostname[0]] * len(ipv4))
    list_int_name.extend(int_name)
    net_connect.disconnect()

df = DataFrame({"IP": list_int, "Hostname": list_hostname, "Interface": list_int_name, "IPv4 Address": list_ipv4, "Netmask": list_netmask})
df.to_excel("Interface_information.xlsx", index=False)

使用Netmiko模組連線Linux伺服器並收集日誌

Netmiko是一個用於連線和管理網路裝置的Python模組,但它同樣可以用於連線Linux伺服器。與Paramiko相比,Netmiko提供了更簡潔的程式碼和更好的輸出結果。

連線Linux伺服器

要使用Netmiko連線Linux伺服器,首先需要匯入Netmiko模組並新增裝置資料,包括IP地址、使用者名稱、密碼和裝置型別(對於Linux裝置,裝置型別應設為"linux")。

from netmiko import Netmiko

host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux"}
    command = "uname -a"
    net_connect = Netmiko(**device)
    output = net_connect.send_command(command, strip_command=False)
    net_connect.disconnect()
    print(f"{ip}:{output}\n")

內容解密:

  1. 匯入Netmiko模組:首先匯入Netmiko類別,這是Netmiko模組的核心,用於建立與裝置的連線。
  2. 定義主機列表:列出需要連線的Linux伺服器的IP地址。
  3. 迴圈連線每個主機:對於每個IP地址,建立一個包含連線必要資訊的字典(包括主機IP、使用者名稱、密碼和裝置型別)。
  4. 執行命令:使用send_command方法在連線的裝置上執行uname -a命令,該命令顯示裝置的主機名、作業系統和版本資訊。
  5. 設定strip_command引數:將strip_command設為False,以便在輸出中包含所執行的命令本身。
  6. 斷開連線並列印輸出:斷開與裝置的連線,並列印出命令的輸出結果。

收集Syslog日誌

Syslog是Linux伺服器上的一個重要檔案,包含了與伺服器相關的所有日誌資料。預設情況下,它位於/var/log/目錄下。

from netmiko import Netmiko

host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux"}
    command = "cat /var/log/syslog"
    net_connect = Netmiko(**device)
    output = net_connect.send_command(command)
    net_connect.disconnect()
    with open(f"{ip}_syslog.txt", "a") as w:
        w.write(output)

內容解密:

  1. 執行cat命令:使用cat命令讀取Syslog檔案的內容。
  2. 儲存輸出到檔案:將命令的輸出儲存到一個以裝置IP命名的文字檔案中。

收集包含SSH相關的日誌並透過電子郵件傳送

可以進一步使用grep命令過濾Syslog中包含SSH或ssh的行,並將結果儲存到個別的檔案中。

from netmiko import Netmiko
import smtplib
from email.message import EmailMessage
import mimetypes

def collect_configuration():
    host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
    for ip in host:
        device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux"}
        command = "cat /var/log/syslog | grep 'SSH\|ssh'"
        net_connect = Netmiko(**device)
        output = net_connect.send_command(command)
        net_connect.disconnect()
        with open(f"{ip}_ssh_syslog.txt", "a") as w:
            w.write(output)
    # 電子郵件傳送程式碼

內容解密:

  1. 使用grep過濾日誌:在cat命令後使用管道和grep命令來過濾包含SSH或ssh的行。
  2. 儲存結果:將過濾後的結果儲存到以裝置IP命名的檔案中。
  3. 電子郵件傳送:利用Python的smtplibemail.message模組將收集的日誌檔案透過電子郵件傳送。

安全地登入伺服器與收集系統資訊

在自動化管理多台伺服器時,安全地處理登入資訊是首要任務。Python的getpass模組提供了一個簡便的方法來安全地輸入密碼,避免在指令碼中直接寫入密碼。

使用getpass模組安全輸入密碼

當需要在指令碼中登入多台裝置時,直接在程式碼中寫入密碼是不安全的。getpass模組允許在執行指令碼時輸入密碼,並隱藏輸入的內容。

範例 8.5:使用getpass模組安全登入伺服器

from netmiko import Netmiko
from getpass import getpass

host = "192.168.163.135"
device = {"host": host, "username": "ubuntu", "password": getpass(), "device_type": "linux"}
command = "uname -a"
net_connect = Netmiko(**device)
show_output = net_connect.send_command(command)
net_connect.disconnect()
print(f"{host}:{show_output}\n")

內容解密:

  1. 匯入必要的模組:Netmiko用於連線網路裝置,getpass用於安全輸入密碼。
  2. 設定目標主機的IP位址和登入資訊,其中密碼透過getpass()函式取得。
  3. 使用Netmiko連線裝置並執行命令,取得輸出後斷開連線。
  4. 輸出結果顯示主機的作業系統資訊。

登入多台裝置

當需要登入多台裝置時,將getpass()的結果指定給變數,並在迴圈中使用該變數,可以避免重複輸入密碼。

範例 8.6:使用安全密碼登入多台裝置

from netmiko import Netmiko
from getpass import getpass

host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
command = "uname -a"
password = getpass()

for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": password, "device_type": "linux"}
    net_connect = Netmiko(**device)
    show_output = net_connect.send_command(command)
    net_connect.disconnect()
    print(f"{ip}:{show_output}\n")

內容解密:

  1. 設定多台主機的IP位址列表。
  2. 使用getpass()在迴圈外取得密碼,並指定給變數password
  3. 在迴圈中,使用相同的密碼連線每一台裝置,執行命令並輸出結果。

收集CPU和記憶體使用情況

除了登入資訊,收集系統資源使用情況也是常見的需求。可以使用free -mtop -n 1 | grep %Cpu命令分別取得記憶體和CPU使用率。

範例 8.7:收集CPU和記憶體資料

from netmiko import Netmiko
from re import findall
from pandas import DataFrame

memory_total, memory_free, memory_used, cpu_used, host_list = ([] for i in range(5))
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]

for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux"}
    net_connect = Netmiko(**device)
    mem_output = net_connect.send_command("free -m", strip_command=False)
    # 對記憶體輸出的處理
    cpu_output = net_connect.send_command("top -n 1 | grep %Cpu", strip_command=False)
    # 對CPU輸出的處理
    net_connect.disconnect()

內容解密:

  1. 初始化空列表用於儲存收集的資料。
  2. 設定目標主機列表。
  3. 在迴圈中連線每一台主機,執行命令取得記憶體和CPU使用情況。
  4. 對輸出的結果進行處理並儲存。

網路裝置資訊收集與分析

在現代網路管理中,自動化收集裝置資訊成為了一項重要的任務。透過使用像 Netmiko 這樣的函式庫,我們可以輕鬆地連線到多台裝置並收集相關資訊。

CPU 與記憶體使用率收集

首先,我們來看看如何收集伺服器的 CPU 與記憶體使用率。範例 8.7 提供了一個完整的程式碼,展示瞭如何使用 Netmiko 連線到多台 Linux 伺服器,並收集相關資訊。

程式碼範例

from netmiko import Netmiko
from re import findall
from pandas import DataFrame

# 初始化空列表以儲存資料
memory_total, memory_free, memory_used, cpu_used, host_list = ([] for i in range(5))

# 定義要連線的裝置清單
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]

for ip in host:
    # 設定裝置連線引數
    device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux"}
    net_connect = Netmiko(**device)
    
    # 執行命令以收集記憶體和 CPU 使用率資訊
    mem_output = net_connect.send_command("free -m", strip_command=False)
    cpu_output = net_connect.send_command("top -n 1 | grep %Cpu", strip_command=False)
    hostname = findall("@(.*):", net_connect.find_prompt())
    
    # 使用正規表示式提取所需資訊
    total = findall("Mem:\s+(\d+)", mem_output)
    free = findall("Mem:\s+\d+\s+(\d+)", mem_output)
    used = findall("Mem:\s+\d+\s+\d+\s+(\d+)", mem_output)
    cpu = findall("\d+,\d+", cpu_output)
    
    # 將提取的資訊新增到列表中
    memory_total.append(f"{total[0]} MB")
    memory_free.append(f"{free[0]} MB")
    memory_used.append(f"{used[0]} MB")
    cpu_used.append(f"% {cpu[0]}")
    host_list.append(hostname[0])

# 將收集到的資料組織成 DataFrame 並儲存到 Excel 檔案中
df = DataFrame({"Hostname": host_list, "Total Memory": memory_total, "Free Memory": memory_free, "Memory Usage": memory_used, "CPU Usage": cpu_used})
df.to_excel("CPU-Memory Usage.xlsx", index=False)

內容解密:

  1. 初始化與連線:首先,我們匯入必要的模組並初始化用於儲存資料的空列表。然後,我們定義了要連線的裝置 IP 地址清單。
  2. 命令執行與資料提取:在迴圈中,我們對每個裝置建立連線,並執行 free -mtop -n 1 | grep %Cpu 命令以收集記憶體和 CPU 使用率資訊。使用正規表示式提取所需資料。
  3. 資料儲存:將提取的資訊新增到對應的列表中。
  4. 結果輸出:最後,將收集到的資料組織成 DataFrame,並使用 to_excel 方法儲存到 Excel 檔案中。

網路介面資訊收集

接下來,我們將探討如何收集網路介面資訊。範例 8.8 展示瞭如何使用 ifconfig 命令收集介面名稱、IP 地址和網路遮罩等資訊。

程式碼範例

from netmiko import Netmiko
from re import findall
from pandas import DataFrame

# 初始化空列表以儲存資料
list_ipv4, list_netmask, list_int, list_hostname, list_int_name = ([] for i in range(5))

# 定義要連線的裝置清單
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]

for ip in host:
    # 設定裝置連線引數
    device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux"}
    net_connect = Netmiko(**device)
    
    # 執行 ifconfig 命令以收集介面資訊
    output = net_connect.send_command("ifconfig")
    
    # 使用正規表示式提取介面名稱、IP 地址和網路遮罩等資訊
    # ...

內容解密:

  1. 初始化與連線:與前一範例類別似,首先進行必要的初始化和裝置連線設定。
  2. 命令執行與資料提取:執行 ifconfig 命令並收集輸出。使用正規表示式提取介面名稱、IP 地址和網路遮罩等所需資訊。
  3. 資料處理與儲存:將提取的資訊儲存到對應的列表中,並進一步處理這些資料。
  4. 結果輸出:最後,將收集到的介面資訊組織成適當的格式並輸出。