系统运行监控程序

# This is a sample Python script.
import psutil
import platform
import math


# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

def bytesHuman(data):
    if data == 0:
        return 0
    elif data <= 1024:
        return str(data) + "Bytes"
    elif data <= 1048576:
        return str(math.ceil(data / 1024)) + "KB"
    elif data < 1073741824:
        return str(round((data / 1024 / 1024), 2)) + "MB"
    else:
        return str(math.ceil(data / 1024 / 1024 / 1024)) + "GB"


def monitor(name):
    print(name)
    print("CPU信息:")
    print("CPU物理核心数量:", psutil.cpu_count(False))
    print("CPU逻辑核心数量:", psutil.cpu_count())
    print()

    print("内存信息:")
    print("内存总量:", bytesHuman(psutil.virtual_memory().total))
    print("内存使用量:", bytesHuman(psutil.virtual_memory().used))
    if platform.system() == "Linux":
        print("内存缓冲量:", bytesHuman(psutil.virtual_memory().buffers))
        print("内存缓存使用量:", bytesHuman(psutil.virtual_memory().cached))
    print("内存空闲总量:", bytesHuman(psutil.virtual_memory().free))
    print("交换分区总量:", bytesHuman(psutil.swap_memory().total))
    print("交换分区使用量:", bytesHuman(psutil.swap_memory().used))
    print("交换分区空闲量:", bytesHuman(psutil.swap_memory().free))
    print()

    print("磁盘情况:")
    for part in psutil.disk_partitions():
        print("\t盘符:", part.device)
        print("\t挂载点:", part.mountpoint)
        print("\t文件系统类型:", part.fstype)
        print("\t权限:", part.opts)
        print("\t最大目录数量:", part.maxfile)
        print("\t最大目录层级:", part.maxpath)
        print()

    disks = psutil.disk_io_counters(True)
    for disk in disks:
        print("磁盘:", disk)
        print("磁盘读io数:", disks[disk].read_count)
        print("磁盘写io数:", disks[disk].write_count)
        print("磁盘读字节数:", bytesHuman(disks[disk].read_bytes))
        print("磁盘写字节数:", bytesHuman(disks[disk].write_bytes))
        print()

    # 网络协议
    net_id = {}
    for net in psutil.net_connections():
        net_id[net.pid] = net
        
    print("当前系统进程:")
    for proc in psutil.process_iter():
        try:
            port = net_id[proc.pid].laddr.port
            print("进程ID:%d,父进程ID:%d,进程:%s,网络端口:%s" % (proc.pid, proc.ppid(), proc.name(), port))
        except psutil.NoSuchProcess:
            pass
        except KeyError:
            print("进程ID:%d,父进程ID:%d,进程:%s" % (proc.pid, proc.ppid(), proc.name()))


if __name__ == '__main__':
    monitor("this is simple system monitor program\n")

 

posted @ 2024-01-11 09:57  TongXiaLi  阅读(13)  评论(0编辑  收藏  举报