溫馨提示×

linux中python命令能進行哪些系統監控

小樊
104
2024-12-09 11:06:05
欄目: 編程語言

在Linux中,可以使用Python編寫腳本來監控系統資源、進程、網絡連接等

  1. 監控CPU使用率:
import os
import time

while True:
    cpu_usage = os.popen("top -bn1 | grep 'Cpu(s)' | sed 's/.*, *\([0-9.]*\)%* id.*/\1/' | awk '{print 100 - $1}'").read()
    print("CPU使用率:", cpu_usage)
    time.sleep(5)
  1. 監控內存使用情況:
import os
import time

while True:
    memory_usage = os.popen("free -m | awk 'NR==2{printf \"%.2f%%\", $3*100/$2 }'").read()
    print("內存使用率:", memory_usage)
    time.sleep(5)
  1. 監控磁盤空間:
import os
import time

while True:
    disk_usage = os.popen("df -h | awk '$NF==\"/\"{printf \"%s\", $5}'").read()
    print("磁盤空間使用率:", disk_usage)
    time.sleep(5)
  1. 監控網絡流量:
import os
import time

def get_network_traffic():
    net_io = os.popen("ifconfig | grep 'bytes' | awk '{print $2}'").read()
    net_io = net_io.split('\n')[0]
    in_bytes, out_bytes = map(int, net_io.split(','))
    return in_bytes, out_bytes

while True:
    in_bytes, out_bytes = get_network_traffic()
    print("上傳流量:", in_bytes / (1024 * 1024), "MB/s")
    print("下載流量:", out_bytes / (1024 * 1024), "MB/s")
    time.sleep(5)
  1. 監控進程:
import os
import time

def get_process_info():
    process_info = os.popen("ps aux --sort=-%cpu").read()
    return process_info

while True:
    print("進程信息:\n", get_process_info())
    time.sleep(5)

這些示例腳本僅用于監控基本系統資源。你可以根據需要修改和擴展這些腳本,以適應你的需求。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女