溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python Linux系統(tǒng)監(jiān)控腳本編寫

發(fā)布時(shí)間:2024-09-11 21:32:34 來源:億速云 閱讀:79 作者:小樊 欄目:編程語言

在Linux系統(tǒng)中,可以使用Python編寫一個(gè)簡(jiǎn)單的系統(tǒng)監(jiān)控腳本

import os
import time

def get_cpu_usage():
    with open('/proc/stat', 'r') as f:
        cpu_data = f.readline()
    cpu_data = cpu_data.split()
    total_cpu_time = sum(map(int, cpu_data[1:]))
    idle_cpu_time = int(cpu_data[4])
    return 100 * (total_cpu_time - idle_cpu_time) / total_cpu_time

def get_memory_usage():
    with open('/proc/meminfo', 'r') as f:
        mem_data = f.readlines()
    total_mem = int(mem_data[0].split()[1])
    free_mem = int(mem_data[1].split()[1])
    return 100 * (total_mem - free_mem) / total_mem

def main():
    while True:
        cpu_usage = get_cpu_usage()
        mem_usage = get_memory_usage()
        print(f"CPU Usage: {cpu_usage:.2f}%")
        print(f"Memory Usage: {mem_usage:.2f}%")
        time.sleep(1)

if __name__ == "__main__":
    main()

這個(gè)腳本會(huì)每隔一秒鐘獲取系統(tǒng)的CPU使用率和內(nèi)存使用率,并打印出來。你可以根據(jù)需要修改時(shí)間間隔或者添加其他功能,例如將監(jiān)控?cái)?shù)據(jù)寫入日志文件等。

注意:這個(gè)腳本只適用于Linux系統(tǒng),因?yàn)樗褂昧?code>/proc文件系統(tǒng)來獲取系統(tǒng)信息。在其他操作系統(tǒng)上運(yùn)行此腳本可能會(huì)導(dǎo)致錯(cuò)誤。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI