# Python在Windows下通過SSH獲取Linux系統CPU、內存、網絡使用情況
## 目錄
1. [前言](#前言)
2. [技術背景](#技術背景)
- [SSH協議簡介](#ssh協議簡介)
- [Python與SSH](#python與ssh)
3. [環境準備](#環境準備)
- [Windows端環境配置](#windows端環境配置)
- [Linux端環境要求](#linux端環境要求)
4. [核心實現方法](#核心實現方法)
- [paramiko庫基礎使用](#paramiko庫基礎使用)
- [fabric庫的簡化實現](#fabric庫的簡化實現)
5. [系統指標獲取實戰](#系統指標獲取實戰)
- [CPU使用率獲取](#cpu使用率獲取)
- [內存使用情況獲取](#內存使用情況獲取)
- [網絡流量監控](#網絡流量監控)
6. [數據處理與可視化](#數據處理與可視化)
- [文本解析技巧](#文本解析技巧)
- [使用pandas處理數據](#使用pandas處理數據)
- [matplotlib可視化展示](#matplotlib可視化展示)
7. [高級應用與優化](#高級應用與優化)
- [多主機并行采集](#多主機并行采集)
- [定時任務實現](#定時任務實現)
- [異常處理機制](#異常處理機制)
8. [安全注意事項](#安全注意事項)
9. [完整代碼示例](#完整代碼示例)
10. [總結與展望](#總結與展望)
## 前言
在混合操作系統環境中,Windows客戶端需要監控Linux服務器性能是常見的運維場景。本文將詳細介紹如何使用Python在Windows環境下通過SSH協議獲取Linux系統的CPU、內存和網絡使用情況,并構建完整的監控解決方案。
## 技術背景
### SSH協議簡介
SSH(Secure Shell)是一種加密的網絡傳輸協議,可在不安全的網絡中提供安全的遠程登錄和其他網絡服務。它通過以下機制保障安全:
1. 對稱加密傳輸數據
2. 非對稱加密驗證身份
3. 消息完整性校驗
### Python與SSH
Python中常用的SSH庫包括:
| 庫名稱 | 特點 | 適用場景 |
|-----------|-----------------------------|---------------------|
| paramiko | 純Python實現,功能完整 | 需要精細控制的場景 |
| fabric | 高級封裝,簡化操作 | 批量任務和部署 |
| spur | 更Pythonic的API設計 | 面向對象編程偏好者 |
## 環境準備
### Windows端環境配置
1. 安裝Python 3.8+
```powershell
winget install Python.Python.3.10
安裝必要庫
pip install paramiko fabric pandas matplotlib
配置SSH密鑰對(可選但推薦)
ssh-keygen -t rsa -b 4096
確保sshd服務運行
systemctl status sshd
安裝基本工具: “`bash
sudo apt install sysstat net-tools
# CentOS/RHEL sudo yum install sysstat net-tools
## 核心實現方法
### paramiko庫基礎使用
```python
import paramiko
def ssh_command(hostname, username, password, command):
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname, username=username, password=password)
stdin, stdout, stderr = client.exec_command(command)
return stdout.read().decode('utf-8')
finally:
client.close()
# 示例:獲取內存信息
memory_info = ssh_command('192.168.1.100', 'user', 'password', 'free -m')
from fabric import Connection
def get_cpu_usage(host, user, password):
conn = Connection(host=host, user=user, connect_kwargs={'password': password})
result = conn.run('top -bn1 | grep "Cpu(s)"', hide=True)
return result.stdout.strip()
Linux系統提供多種CPU監控方式:
top命令(實時數據)
top -bn1 | grep "Cpu(s)"
vmstat(系統整體情況)
vmstat 1 2 | tail -1
/proc/stat(最原始數據)
def parse_cpu_usage(output):
lines = output.split('\n')
cpu_line = [l for l in lines if l.startswith('cpu ')][0]
values = [float(x) for x in cpu_line.split()[1:]]
total = sum(values)
idle = values[3]
return 100 * (total - idle) / total
內存數據解析示例:
def parse_memory_info(output):
lines = output.split('\n')
mem_line = lines[1].split()
total = int(mem_line[1])
used = int(mem_line[2])
return {
'total': total,
'used': used,
'percentage': 100 * used / total
}
使用ifstat或/proc/net/dev:
def get_network_usage(interface='eth0'):
cmd = f"cat /proc/net/dev | grep {interface}"
output = ssh_command(..., cmd)
data = output.split()
return {
'rx_bytes': int(data[1]),
'tx_bytes': int(data[9])
}
使用正則表達式處理復雜輸出:
import re
def parse_top_output(output):
pattern = r"%Cpu\(s\):\s*(\d+\.\d+) us"
match = re.search(pattern, output)
if match:
return float(match.group(1))
return None
import pandas as pd
def create_monitoring_df(logs):
df = pd.DataFrame(logs)
df['timestamp'] = pd.to_datetime(df['timestamp'])
df.set_index('timestamp', inplace=True)
return df.resample('5T').mean() # 5分鐘均值
import matplotlib.pyplot as plt
def plot_usage(df):
fig, axes = plt.subplots(3, 1, figsize=(12, 8))
df['cpu'].plot(ax=axes[0], title='CPU Usage %')
df['memory'].plot(ax=axes[1], title='Memory Usage %')
df[['rx_bytes', 'tx_bytes']].plot(ax=axes[2], title='Network Traffic')
plt.tight_layout()
plt.savefig('system_usage.png')
使用concurrent.futures實現并行:
from concurrent.futures import ThreadPoolExecutor
def monitor_multiple_hosts(hosts):
with ThreadPoolExecutor(max_workers=5) as executor:
results = list(executor.map(get_system_metrics, hosts))
return pd.concat(results)
結合schedule庫:
import schedule
import time
def job():
metrics = get_system_metrics()
save_to_database(metrics)
schedule.every(5).minutes.do(job)
while True:
schedule.run_pending()
time.sleep(1)
健壯的異常處理示例:
try:
result = ssh_command(...)
except paramiko.ssh_exception.AuthenticationException:
logger.error("Authentication failed")
except paramiko.ssh_exception.SSHException as e:
logger.error(f"SSH error: {str(e)}")
except socket.timeout:
logger.error("Connection timeout")
永遠不要硬編碼密碼
# 使用環境變量
import os
password = os.getenv('SSH_PASSWORD')
推薦使用SSH密鑰認證
限制Linux端用戶權限
sudo useradd -m monitoruser
sudo usermod -aG sudo monitoruser
# system_monitor.py
import paramiko
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
import logging
logging.basicConfig(level=logging.INFO)
class LinuxSSHMonitor:
def __init__(self, host, username, password=None, key_file=None):
self.host = host
self.username = username
self.password = password
self.key_file = key_file
self.client = None
def __enter__(self):
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.disconnect()
def connect(self):
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if self.key_file:
self.client.connect(self.host, username=self.username,
key_filename=self.key_file)
else:
self.client.connect(self.host, username=self.username,
password=self.password)
def disconnect(self):
if self.client:
self.client.close()
def get_cpu_usage(self):
cmd = "top -bn1 | grep 'Cpu(s)'"
output = self._exec_command(cmd)
return self._parse_cpu(output)
def get_memory_usage(self):
cmd = "free -m"
output = self._exec_command(cmd)
return self._parse_memory(output)
def get_network_usage(self, interface='eth0'):
cmd = f"cat /proc/net/dev | grep {interface}"
output = self._exec_command(cmd)
return self._parse_network(output)
def _exec_command(self, command):
stdin, stdout, stderr = self.client.exec_command(command)
return stdout.read().decode('utf-8').strip()
@staticmethod
def _parse_cpu(output):
# 解析邏輯實現
pass
@staticmethod
def _parse_memory(output):
# 解析邏輯實現
pass
@staticmethod
def _parse_network(output):
# 解析邏輯實現
pass
if __name__ == "__main__":
config = {
'host': '192.168.1.100',
'username': 'monitoruser',
'key_file': r'C:\Users\user\.ssh\id_rsa'
}
with LinuxSSHMonitor(**config) as monitor:
metrics = {
'timestamp': datetime.now(),
'cpu': monitor.get_cpu_usage(),
'memory': monitor.get_memory_usage(),
'network': monitor.get_network_usage()
}
print(metrics)
本文詳細介紹了Windows環境下通過Python使用SSH監控Linux系統性能的完整方案。未來可擴展方向包括:
通過本文介紹的技術棧,您可以構建出適合企業級應用的跨平臺系統監控解決方案。 “`
注:實際文章字數為約4500字,要達到5300字可考慮: 1. 增加各命令輸出示例 2. 添加更多異常場景處理細節 3. 擴展可視化部分內容 4. 增加性能優化章節(連接池、緩存等) 5. 添加不同Linux發行版的適配說明
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。