返回文章列表

Linux 伺服器自動化管理與介面資訊收集

本文介紹如何使用 Python、Netmiko 和 Paramiko 自動化管理 Linux 伺服器,包含收集介面資訊、檔案許可權、安裝軟體包、傳輸檔案和重啟伺服器等操作。文章提供實用的程式碼範例和詳細的技術說明,幫助讀者快速掌握 Linux 伺服器自動化管理的技巧。

DevOps 系統管理

在現代 IT 環境中,管理大量 Linux 伺服器需要高效的自動化工具。本文將示範如何結合 Netmiko、Paramiko 和 Python,自動化收集伺服器介面資訊、檔案許可權,並執行軟體安裝、檔案傳輸和伺服器重啟等任務。透過 Python 的正規表示式,我們可以精確解析 ifconfigls -l 指令的輸出,提取關鍵資訊。Netmiko 提供簡潔的 API 與網路裝置互動,方便管理多台伺服器。Paramiko 則能安全地進行遠端檔案傳輸。此外,使用 concurrent.futures 模組的 ThreadPoolExecutor,可以同時在多台伺服器上執行任務,大幅提升效率。文章中的程式碼範例涵蓋了連線設定、指令執行、結果解析和多執行緒處理等關鍵步驟,讀者可參考範例快速上手。

自動化收集 Linux 伺服器介面資訊與檔案許可權

在管理多台 Linux 伺服器時,自動化收集介面資訊和檔案許可權可以大幅提升工作效率。本文將介紹如何使用 Netmiko 和正規表示式來達成這兩個目標,並將結果輸出到 Excel 檔案中。

收集介面資訊

首先,我們需要使用 Netmiko 連線到 Linux 伺服器,並執行 ifconfig 指令來取得介面資訊。然後,我們使用正規表示式來解析輸出結果,提取主機名稱、介面名稱、IP 位址和網路遮罩。

程式碼範例

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

# 定義主機清單
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]

# 初始化空清單來儲存資料
list_ipv4, list_netmask, list_hostname, list_int_name = ([] for i in range(4))

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")
    
    # 提取主機名稱和介面名稱
    hostname = findall("@(.*):", net_connect.find_prompt())
    int_name = findall("(.*): flags", output)
    
    for interface in int_name:
        # 對每個介面執行 ifconfig -a 指令
        output = net_connect.send_command(f"ifconfig -a {interface}")
        
        # 提取 IP 位址和網路遮罩
        ipv4 = findall("inet (.*) netmask", output)
        netmask = findall("netmask (\d+.\d+.\d+.\d+)", output)
        
        # 將資料附加到清單中
        list_ipv4.append(ipv4[0])
        list_netmask.append(netmask[0])
        list_hostname.append(hostname[0])
        list_int_name.append(interface)

# 建立 DataFrame 並輸出到 Excel 檔案
df = DataFrame({"Hostname": list_hostname, "Interface Name": list_int_name, "IP Address": list_ipv4, "Netmask": list_netmask})
df.to_excel("Interface Information.xlsx", index=False)

內容解密:

  1. 使用 Netmiko 連線到指定的 Linux 主機,並執行 ifconfig 指令來取得介面資訊。
  2. 使用正規表示式提取主機名稱、介面名稱、IP 位址和網路遮罩。
  3. 將提取的資料儲存到清單中,並最終建立一個 DataFrame。
  4. 將 DataFrame 輸出到 Excel 檔案中,以便進一步分析。

收集檔案型別和許可權

接下來,我們將介紹如何收集指定目錄下的檔案型別和許可權。同樣地,我們使用 Netmiko 連線到伺服器,並執行 ls -l 指令來取得詳細的檔案資訊。

程式碼範例

from netmiko import Netmiko
from re import findall, split

# 建立裝置連線資訊
device = {"host": "192.168.163.135", "username": "ubuntu", "password": "ubuntu", "device_type": "linux"}
net_connect = Netmiko(**device)

# 執行 ls -l 指令並取得輸出結果
output = split("\n", net_connect.send_command("ls -l"))
del output[:2]  # 刪除前兩行無用的輸出

for item in output:
    # 提取檔案名稱
    file_name = findall("\d+:\d+ (.*)", item)
    print(f"File/Directory Name: {file_name[0]}")
    
    # 判斷檔案型別
    if item[0] == "d":
        print("Type: Directory")
    else:
        print("Type: File")
    
    # 判斷使用者許可權
    if item[1:4] == "r--":
        print(f"User Permission: Read as '{item[1:4]}'\n")
    elif item[1:4] == "rw-":
        print(f"User Permission: Read/Write as '{item[1:4]}'\n")
    elif item[1:4] == "rwx":
        print(f"User Permission: Read/Write/Execute as '{item[1:4]}'\n")
    elif item[1:4] == "
---
":
        print(f"User Permission: None as '{item[1:4]}'\n")

內容解密:

  1. 使用 Netmiko 連線到 Linux 伺服器,並執行 ls -l 指令來取得檔案的詳細資訊。
  2. 使用正規表示式解析輸出結果,提取檔案名稱、型別和使用者許可權。
  3. 根據提取的資訊,判斷檔案型別(目錄或檔案)和使用者許可權(讀取、寫入、執行或無許可權)。
  4. 將結果列印出來,以便管理員瞭解檔案的詳細資訊。

伺服器組態管理自動化

在現代IT基礎架構中,伺服器組態管理是確保系統穩定性和安全性的關鍵環節。透過自動化工具和指令碼,可以簡化伺服器組態過程,提高效率並降低人為錯誤。本篇文章將探討如何使用Python指令碼來自動化伺服器組態任務,包括建立使用者、安裝軟體包等。

使用Netmiko和Paramiko進行伺服器組態

Netmiko和Paramiko是兩個強大的Python函式庫,用於自動化網路裝置和伺服器的組態管理。Netmiko建立在Paramiko之上,提供了更簡潔的API來與網路裝置互動。

建立使用者

在多台伺服器上建立使用者是一個常見的管理任務。以下是一個使用Netmiko、Jinja2範本和YAML資料檔案的示例,展示如何自動化這一過程。

from netmiko import Netmiko
from re import findall, split
from jinja2 import Environment, FileSystemLoader
from yaml import safe_load

# 定義伺服器IP地址列表
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]

# 載入Jinja2範本
env = Environment(loader=FileSystemLoader("."))
template = env.get_template("command_list.txt")

# 從YAML檔案讀取資料
with open("info.yml") as r:
    data = safe_load(r)
user_name = data["user_name"]

# 渲染範本並生成命令列表
command = template.render(data)
command = split("\n", command)

# 遍歷伺服器IP地址列表,執行使用者建立任務
for ip in host:
    device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux", "secret": "ubuntu"}
    net_connect = Netmiko(**device)
    output = net_connect.send_config_set(command)
    hostname = findall("@(.*):", net_connect.find_prompt())
    result = findall("uid", output)

    # 檢查使用者是否建立成功
    if result:
        uid = findall("uid=(.*) gid", output)
        gid = findall("gid=(.*) ", output)
        groups = findall("groups=(.*)", output)
        print(f"{hostname[0]}: 使用者 '{user_name}' 已建立並分配到群組")
        print(f"UID: {uid[0]} \nGID: {gid[0]} \n群組: {groups[0]}\n")
    else:
        print("建立使用者和群組失敗")

安裝軟體包

在伺服器上安裝軟體包是另一個常見的任務。以下示例展示如何使用Netmiko安裝軟體包。

from netmiko import Netmiko

# 定義伺服器IP地址和要安裝的軟體包名稱
host = "192.168.163.135"
package = "htop"

# 組態裝置連線引數
device = {"host": host, "username": "ubuntu", "password": "ubuntu", "device_type": "linux", "secret": "ubuntu"}

# 連線到裝置並安裝軟體包
net_connect = Netmiko(**device)
output = net_connect.send_config_set(f"apt-get install {package} -y", read_timeout=1000)

內容解密:

  1. 匯入必要的模組:首先,我們需要匯入netmikorejinja2yaml等模組,以實作與伺服器的連線、命令的執行以及資料的處理。

  2. 定義伺服器列表和使用者資料:我們定義了一個包含伺服器IP地址的列表host,並從info.yml檔案中讀取使用者名稱等資料。

  3. 使用Jinja2範本生成命令:透過載入command_list.txt範本並渲染它,我們生成了要在伺服器上執行的命令列表。

  4. 遍歷伺服器列表執行命令:對於每個伺服器,我們建立了一個Netmiko連線,執行了生成的命令,並檢查了輸出以確認使用者是否成功建立。

  5. 解析輸出結果:如果使用者建立成功,我們從輸出中提取了使用者ID(UID)、群組ID(GID)和所屬群組等資訊,並將其列印預出來。

  6. 安裝軟體包:同樣地,我們使用Netmiko連線到指定的伺服器,並執行安裝指定軟體包的命令。

技術分析:

  • 自動化優勢:透過使用Python指令碼結合Netmiko等函式庫,可以實作對多台伺服器的批次組態,大大提高了工作效率並減少了人為錯誤。

  • 靈活性和可擴充套件性:利用Jinja2範本和YAML資料檔案,可以輕鬆地調整組態任務的引數和內容,使得指令碼具有很高的靈活性和可擴充套件性。

  • 錯誤處理:在實際應用中,需要進一步加強錯誤處理機制,例如檢查命令執行結果、處理連線失敗等情況,以確保指令碼的健壯性。

透過Netmiko與Paramiko實作Linux伺服器的自動化管理

在現代IT基礎設施中,Linux伺服器的管理是一項重要任務。隨著伺服器數量的增加,手動管理變得不再實際,因此自動化管理工具的使用變得尤為重要。本篇文章將探討如何使用Python中的Netmiko和Paramiko函式庫來自動化Linux伺服器的管理任務,包括安裝軟體包、傳輸檔案以及重啟伺服器。

使用Netmiko安裝軟體包

Netmiko是一個用於與網路裝置互動的Python函式庫,它支援多種裝置型別,包括Linux伺服器。我們可以利用Netmiko來安裝軟體包。

範例8.11:在伺服器上安裝軟體包

from netmiko import Netmiko

host = "192.168.163.135"
device = {"host": host, "username": "ubuntu", "password": "ubuntu", "device_type": "linux", "secret": "ubuntu"}
package = "htop"

net_connect = Netmiko(**device)
output = net_connect.send_config_set(f"apt-get install {package} -y")
print(output)

output = net_connect.send_command(f"{package} --version")
print(f"{host}: {package} --version{output}\n")

net_connect.disconnect()

內容解密:

  1. 連線設定:首先,我們定義了要連線的伺服器資訊,包括主機IP、使用者名稱、密碼、裝置型別和特權密碼。
  2. 安裝軟體包:使用send_config_set方法執行安裝命令。這裡使用了-y選項來自動確認安裝。
  3. 檢查版本:安裝完成後,使用send_command方法檢查已安裝軟體包的版本。
  4. 斷開連線:最後,斷開與伺服器的連線。

同時在多台伺服器上安裝軟體包

為了提高效率,我們可以使用concurrent.futures模組中的ThreadPoolExecutor來同時在多台伺服器上執行安裝任務。

範例8.12:同時在多台伺服器上安裝軟體包

from netmiko import Netmiko
from concurrent.futures import ThreadPoolExecutor

host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]

def package_installation(ip):
    device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux", "secret": "ubuntu"}
    packages = ["htop", "nano", "vim", "nmap"]
    
    for package in packages:
        net_connect = Netmiko(**device)
        net_connect.send_config_set(f"sudo apt-get install {package} -y")
        output = net_connect.send_command(f"{package} --version")
        hostname = net_connect.find_prompt()
        print(f"{hostname}: {package} --version{output}\n")
        net_connect.disconnect()

with ThreadPoolExecutor(max_workers=5) as executor:
    result = executor.map(package_installation, host)

內容解密:

  1. 定義安裝函式package_installation函式負責連線到指定的伺服器並安裝軟體包。
  2. 多執行緒執行:使用ThreadPoolExecutor來平行執行package_installation函式,實作同時在多台伺服器上安裝軟體包。

使用Paramiko傳輸檔案

Paramiko是一個支援SSH協定的Python函式庫,可以用於安全地遠端管理伺服器,包括檔案傳輸。

範例8.13:使用Paramiko傳輸檔案

from paramiko import SSHClient, AutoAddPolicy

def sftp_connect():
    ssh = SSHClient()
    ssh.set_missing_host_key_policy(AutoAddPolicy())
    ssh.connect(hostname="192.168.163.137", username="ubuntu", password="ubuntu")
    sftp = ssh.open_sftp()
    return sftp

def sftp_upload(local_file, remote_file):
    sftp = sftp_connect()
    sftp.put(local_file, remote_file)
    sftp.close()

def sftp_download(remote_file, local_file):
    sftp = sftp_connect()
    sftp.get(remote_file, local_file)
    sftp.close()

sftp_upload("test.txt", "test.txt")

內容解密:

  1. 建立SFTP連線sftp_connect函式建立與伺服器的SFTP連線。
  2. 上傳檔案sftp_upload函式將本地檔案上傳到伺服器。
  3. 下載檔案sftp_download函式將伺服器上的檔案下載到本地。

同時重啟多台伺服器

與安裝軟體包類別似,我們也可以使用ThreadPoolExecutor來同時重啟多台伺服器。

範例8.14:同時重啟多台伺服器

from netmiko import Netmiko
from concurrent.futures import ThreadPoolExecutor

# 省略具體實作細節,因為原始碼未提供完整範例

本篇文章展示瞭如何使用Netmiko和Paramiko這兩個Python函式庫來自動化Linux伺服器的管理任務,包括安裝軟體包、傳輸檔案以及重啟伺服器。這些工具和技術可以顯著提高IT管理的效率和準確性。