要使用Python監控Linux系統狀態,您可以使用psutil庫
pip install psutil
接下來,您可以使用以下示例代碼來監控Linux系統的CPU使用率、內存使用情況、磁盤空間和網絡接口:
import psutil
import time
def monitor_system_status():
while True:
cpu_usage = psutil.cpu_percent(interval=1)
memory_usage = psutil.virtual_memory().percent
disk_space = psutil.disk_usage('/').percent
network_io = psutil.net_io_counters()
print(f"CPU使用率: {cpu_usage}%")
print(f"內存使用率: {memory_usage}%")
print(f"磁盤空間: {disk_space}%")
print(f"網絡接口: {network_io}")
time.sleep(5) # 每隔5秒監控一次
if __name__ == "__main__":
monitor_system_status()
將上述代碼保存為一個名為monitor_system.py的文件,然后在終端中運行它:
python monitor_system.py
這將啟動一個無限循環,每隔5秒打印一次系統狀態。您可以根據需要修改間隔時間或添加其他監控功能。