現代 IT 環境中,管理大量 Linux 伺服器需要自動化工具提升效率和降低錯誤率。Netmiko 模組提供簡潔的 Python 介面,方便進行遠端 SSH 連線和指令執行。本文將示範如何使用 Netmiko 重啟伺服器、停止特定程式,並結合 concurrent.futures 模組實作平行處理,大幅縮短操作時間。此外,文章也探討 Firewalld 服務的管理,包含狀態檢查、啟動/停止、開機設定等,並提供 Python 自動化指令碼範例,簡化複雜的防火牆組態流程。
遠端管理 Linux 伺服器的進階應用:使用 Netmiko 模組
在現代 IT 環境中,系統管理員經常需要同時管理多台 Linux 伺服器。手動逐一登入每台伺服器執行相同操作不僅耗時耗力,還容易出錯。因此,使用自動化工具來簡化這些任務變得尤為重要。本篇文章將探討如何使用 Python 的 Netmiko 模組來遠端管理多台 Linux 伺服器,包括重啟伺服器、停止特定程式等操作。
重啟多台 Linux 伺服器
在某些情況下,系統管理員需要同時重啟多台伺服器。例如,當進行核心更新或系統維護時,重啟是必要的步驟。手動重啟每台伺服器不僅效率低下,還可能導致部分伺服器被遺忘。以下是一個使用 Netmiko 和 concurrent.futures 模組來同時重啟多台 Linux 伺服器的範例。
from netmiko import Netmiko
from re import findall
from concurrent.futures import ThreadPoolExecutor
# 定義目標主機的 IP 地址
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
command = "reboot"
def netmiko_reboot(ip):
# 設定連線裝置的引數
device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux", "secret": "ubuntu"}
net_connect = Netmiko(**device)
# 取得主機名稱
hostname = findall("@(.*):", net_connect.find_prompt())
print(f"
---
正在重啟:{hostname[0]}
---
")
# 執行重啟命令
net_connect.send_config_set(command)
return
# 使用 ThreadPoolExecutor 來平行執行重啟任務
with ThreadPoolExecutor(max_workers=5) as executor:
result = executor.map(netmiko_reboot, host)
程式碼解析:
- 匯入必要的模組:
netmiko用於建立 SSH 連線,re用於正規表示式匹配,concurrent.futures用於平行處理。 - 定義目標主機和命令:指定需要重啟的伺服器 IP 地址和要執行的命令(
reboot)。 netmiko_reboot函式:該函式負責連線到指定的伺服器,取得主機名稱,並執行重啟命令。- 平行執行:使用
ThreadPoolExecutor來平行執行netmiko_reboot函式,從而同時重啟多台伺服器。
停止特定程式
除了重啟伺服器外,系統管理員還可能需要遠端停止特定的程式。例如,當某個應用程式無回應或需要更新時,需要先終止其相關程式。以下是一個使用 Netmiko 來停止特定程式的範例。
from netmiko import Netmiko
from re import findall
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 = "ps fax"
process = "gnome-calculator"
net_connect = Netmiko(**device)
output = net_connect.send_command(command)
hostname = findall("@(.*):", net_connect.find_prompt())
pid = findall(f"(\d+).*{process}", output)
if pid:
net_connect.send_command(f"kill {pid[0]}")
output = net_connect.send_command(command)
pid_new = findall(f"(\d+).*{process}", output)
if not pid_new:
print(f"{hostname[0]} '{process}' 程式(PID:{pid[0]})已成功終止。")
else:
print(f"{hostname[0]} '{process}' 程式(PID:{pid[0]})終止失敗。")
else:
print(f"{hostname[0]} 上未發現 '{process}' 程式。")
程式碼解析:
- 取得程式列表:使用
ps fax命令列出目前執行的程式。 - 查詢特定程式的 PID:透過正規表示式匹配輸出結果,找出目標程式的 PID。
- 終止程式:如果找到目標程式,則使用
kill命令終止該程式,並再次檢查該程式是否已被終止。 - 輸出結果:根據操作結果輸出相應的訊息,指示程式是否成功終止或未被發現。
網路安全與Python
本章節將重點介紹網路和系統裝置的安全特徵和服務。我們將使用netmiko模組連線裝置以檢查和組態安全服務。同時,我們也會透過Python指令碼傳送警示,如果機器中有危險的組態,並且我們將在封包層級檢查網路以深入調查任何問題。
本章節涵蓋以下主題
- 啟用安全服務
- 在伺服器上安裝和啟用“Firewalld”服務
- 組態伺服器上的防火牆設定
- 在網路裝置中建立存取控制列表
- 使用Scapy操作網路封包
- 檢查日誌和組態
- 使用Crontab定期檢查CPU使用率
- 檢查路由器組態中的不安全密碼
- 檢查路由器中的埠安全組態
- 使用Pyshark從埠收集封包
目標
我們將在Linux伺服器上安裝firewalld服務以組態安全特徵。我們將學習如何使用Linux命令來使用此服務,並根據需求啟用或停用它。同時,我們也將建立新的安全區域並進行組態,以允許存取特定的埠、服務和IP地址。
此外,我們將使用Jinja範本在網路裝置中組態存取控制列表(ACL)。我們還將使用Scapy模組操作網路封包,傳送ICMP請求封包,取得ICMP回應封包,並在Wireshark工具中進行檢查。另外,我們將從網路裝置收集資料,以檢查是否存在任何危險的設定,並使用Pyshark模組捕捉網路封包(包含完整詳細資訊)。
啟用安全服務
在本文中,我們將重點介紹網路和系統裝置中的安全服務。我們使用防火牆服務、ACL或流量策略來保護網路和系統環境免受外部攻擊。
在伺服器上安裝和啟用“Firewalld”服務
我們使用firewalld服務作為保護伺服器的第一步。它是一個Linux作業系統防火牆管理工具或服務,也是用Python語言編寫的。
Firewalld支援動態管理防火牆系統,包括網路區域。它根據對網路或協定的信任,無論是在網路內部還是外部。它支援IPv4和IPv6地址設定。
我們可以在輸入組態的同時對此服務進行變更。因此,它是一個執行階段環境,無需重新啟動服務或守護程式。
在許多Linux發行版中,例如CentOS、Fedora和SUSE,預設已安裝Firewalld服務。我們需要在Ubuntu中下載並安裝Firewalld服務才能使用它。
在開始使用Firewalld服務之前,我們需要使用以下命令安裝它:
$ sudo apt install firewalld
所有Firewalld服務命令都需要管理員帳戶。因此,在每個命令的開頭,我們應該新增sudo命令以進入根使用者或管理員使用者。
安裝與啟動Firewalld服務的步驟
- 安裝Firewalld:使用
sudo apt install firewalld命令進行安裝。 - 切換到根使用者:使用
sudo -s命令切換到根使用者,以避免在每個命令前輸入sudo。ubuntu@Server-1:~$ sudo -s [sudo] password for ubuntu: root@Server-1:/home/ubuntu# - 啟動Firewalld服務:使用
systemctl start firewalld命令啟動服務。root@Server-1:/home/ubuntu# systemctl start firewalld - 驗證Firewalld服務狀態:使用
firewall-cmd --state命令檢查Firewalld服務是否正在執行。如果輸出結果為“running”,則表示Firewalld服務正在執行。root@Server-1:/home/ubuntu# firewall-cmd --state running
詳細解說:
systemctl命令:這是一個Linux服務管理命令,用於檢查伺服器上安裝的任何服務的狀態。我們可以透過輸入systemctl status SERVICE_NAME來檢查每個服務的狀態。firewall-cmd --state命令:用於檢查Firewalld服務的狀態。它只會顯示服務是否正在執行。
使用Systemctl管理服務
systemctl是一個功能強大的工具,用於管理Linux系統上的服務。以下是一些基本用法:
- 啟動服務:
systemctl start SERVICE_NAME - 停止服務:
systemctl stop SERVICE_NAME - 重啟服務:
systemctl restart SERVICE_NAME - 檢查服務狀態:
systemctl status SERVICE_NAME
內容解密:
systemctl start firewalld:這個命令用於啟動Firewalld服務。Firewalld是一種動態防火牆管理工具,可以根據需要動態地更新防火牆規則,而無需重新啟動服務。firewall-cmd --state:這個命令用於檢查Firewalld服務的當前狀態。如果傳回“running”,則表示Firewalld正在執行並且生效。
管理Linux系統中的firewalld服務
在Linux系統中,firewalld是一個動態防火牆守護程式,提供了一個簡單的方式來管理防火牆規則。在本篇文章中,我們將探討如何使用systemctl命令來管理firewalld服務,並使用Python腳原本自動化這些任務。
檢查firewalld服務的狀態
要檢查firewalld服務的狀態,可以使用systemctl status firewalld命令。這個命令會顯示服務的詳細資訊,包括其載入目錄、活動狀態、程式ID、任務數量和資源使用情況。
root@Server-1:/home/ubuntu# systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: active (running) since Sat 2022-09-10 16:42:31 +03; 3s ago
Docs: man:firewalld(1)
Main PID: 2625 (firewalld)
Tasks: 2 (limit: 4584)
Memory: 22.6M
CPU: 672ms
CGroup: /system.slice/firewalld.service
└─2625 /usr/bin/Python3 /usr/sbin/firewalld --nofork --nopid
Aug 10 16:42:31 Server-1 systemd[1]: Starting firewalld - dynamic firewall daemon...
Aug 10 16:42:31 Server-1 systemd[1]: Started firewalld - dynamic firewall daemon.
停止和啟動firewalld服務
要停止firewalld服務,可以使用systemctl stop firewalld命令。停止服務後,可以使用systemctl status firewalld命令來檢查服務的狀態。
root@Server-1:/home/ubuntu# systemctl stop firewalld
root@Server-1:/home/ubuntu# systemctl status firewalld
firewalld.service - firewalld - dynamic firewall daemon
Loaded: loaded (/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
Active: inactive (dead) since Sat 2022-09-10 16:53:10 +03; 8s ago
Docs: man:firewalld(1)
Process: 2799 ExecStart=/usr/sbin/firewalld --nofork --nopid (code=exited, status=0/SUCCESS)
Main PID: 2799 (code=exited, status=0/SUCCESS)
CPU: 389ms
Aug 10 16:45:52 Server-1 systemd[1]: Starting firewalld - dynamic firewall daemon...
Aug 10 16:45:52 Server-1 systemd[1]: Started firewalld - dynamic firewall daemon.
Aug 10 16:53:10 Server-1 systemd[1]: Stopping firewalld - dynamic firewall daemon...
Aug 10 16:53:10 Server-1 systemd[1]: firewalld.service: Deactivated successfully.
Aug 10 16:53:10 Server-1 systemd[1]: Stopped firewalld - dynamic firewall daemon.
在啟動時啟用或停用firewalld服務
要啟用或停用firewalld服務在啟動時,可以使用systemctl enable或systemctl disable命令。
root@Server-1:/home/ubuntu# systemctl enable firewalld
root@Server-1:/home/ubuntu# systemctl list-unit-files --type=service | grep firewalld
firewalld.service enabled
root@Server-1:/home/ubuntu# systemctl disable firewalld
Removed /etc/systemd/system/multi-user.target.wants/firewalld.service.
Removed /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
root@Server-1:/home/ubuntu# systemctl list-unit-files --type=service | grep firewalld
firewalld.service disabled
使用Python自動化firewalld服務管理
我們可以使用Python的Netmiko函式庫來自動化firewalld服務的管理。以下是一個示例程式碼,展示瞭如何使用Python來連線多個Linux伺服器並管理firewalld服務。
程式碼片段:
from netmiko import Netmiko
from concurrent.futures import ThreadPoolExecutor
host = ["192.168.163.135", "192.168.163.136", "192.168.163.137"]
def server_connection(ip):
device = {"host": ip, "username": "ubuntu", "password": "ubuntu", "device_type": "linux", "secret": "ubuntu"}
net_connect = Netmiko(**device)
return net_connect
內容解密:
這段程式碼首先匯入了必要的函式庫,包括Netmiko和ThreadPoolExecutor。然後定義了一個包含多個Linux伺服器IP地址的列表。server_connection函式用於建立與伺服器的連線,傳回一個Netmiko物件,用於後續的操作。
圖表說明:
此圖示展示了使用Python指令碼管理多個Linux伺服器上的firewalld服務的流程。
@startuml
skinparam backgroundColor #FEFEFE
skinparam componentStyle rectangle
title Netmiko 自動化遠端管理 Linux 伺服器
package "安全架構" {
package "網路安全" {
component [防火牆] as firewall
component [WAF] as waf
component [DDoS 防護] as ddos
}
package "身份認證" {
component [OAuth 2.0] as oauth
component [JWT Token] as jwt
component [MFA] as mfa
}
package "資料安全" {
component [加密傳輸 TLS] as tls
component [資料加密] as encrypt
component [金鑰管理] as kms
}
package "監控審計" {
component [日誌收集] as log
component [威脅偵測] as threat
component [合規審計] as audit
}
}
firewall --> waf : 過濾流量
waf --> oauth : 驗證身份
oauth --> jwt : 簽發憑證
jwt --> tls : 加密傳輸
tls --> encrypt : 資料保護
log --> threat : 異常分析
threat --> audit : 報告生成
@enduml
此圖示說明瞭指令碼的執行流程,從連線伺服器到管理firewalld服務的整個過程。
透過這種方式,我們可以輕鬆地在多個伺服器上自動化管理firewalld服務,提高了管理的效率和安全性。