在Linux中,可以使用Python编写脚本来监控系统资源、进程、网络连接等
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)
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)
import os
import time
while True:
disk_usage = os.popen("df -h | awk '$NF==\"/\"{printf \"%s\", $5}'").read()
print("磁盘空间使用率:", disk_usage)
time.sleep(5)
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)
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)
这些示例脚本仅用于监控基本系统资源。你可以根据需要修改和扩展这些脚本,以适应你的需求。