psutil获取ip对应的网卡使用率

本文档展示了如何使用Python获取CPU运行时间、服务器IP和网卡带宽,通过定时抓取和计算,监控服务器性能并分析网络流量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

from datetime import datetime
import re
import psutil
import time

"""
获取cpu运行时间 int
"""
def get_sysinfo():
    sysInfo={}

    #获取系统上电时间
    bootTime = psutil.boot_time()
    now_time = datetime.now()
    nowtime = now_time.timestamp()
    delta_time = nowtime - bootTime
    print("time:",delta_time)
    print(time.ctime( round(delta_time)))
    sysInfo["time"] = int(str(delta_time).split('.')[0])
    return sysInfo


"""
获取服务器IP 
"""
def get_ipinfo():
    try:
        ipInfo = []
        ip_info = {}
        info = psutil.net_if_addrs()
        for k,v in info.items():
            for item in v:
                if item[0] == 2 and not item[1]=='127.0.0.1' and not item[1]=='192.168.100.1':
                    ipInfo.append((k,item[1]))
        ip_info = tuple(ipInfo)
        ip_info_str = dict(ip_info)
    except Exception as e:
        print("get ipInfo error")
    print("get ipInfo ip_info_str:%s" % (ip_info_str))
    return (ip_info_str) 

"""
获取网卡带宽
"""
def get_netbandwidth_info():
        widthInfo = []
        windthList = []
        windth_info = {}
        #获取网卡IP信息get_ipinfo
        ipInfo = get_ipinfo()
        netName =list(ipInfo.keys())
        info = psutil.net_if_stats()
        print("info :%s" % (info))

        for widthInfo in info.items():
            print("widthInfo:",widthInfo)
            strspeed = widthInfo[1].__str__()
            speedName = widthInfo[0].__str__()
            if speedName == '\x01':
                widthTemp = netName[0]
                print("get bandWidth net name:%s" % (widthTemp))
            else:
                widthTemp = widthInfo[0].__str__()
            str1 = re.split('\W+', strspeed)
            windthList.append((widthTemp,float(str1[-4])))
        windth_info = tuple(windthList)
        windth_info_str = dict(windth_info)
        print("windth_info_str:",windth_info_str)
        return windth_info_str
 #只获取网络带宽
def __check_speeds():
    rs = {}
    for net_name,stats in psutil.net_if_stats().items():
        if type(stats) is tuple or not stats.isup:
            continue
        rs[net_name] = stats.speed
    return rs
def __snapshoot():
    rs = {}
    for net_name,stats in psutil.net_io_counters(pernic=True).items():
        rs[net_name] = stats.bytes_recv
    return rs
 
if __name__=='__main__':
    nets = __check_speeds()
    # print('check speed:',nets)
    while True:
        time.sleep(3)
        print("###########################")
        print(get_sysinfo())
        str = get_netbandwidth_info()
        print("以太网:",str['以太网'])
        snap_prev = __snapshoot()
        time.sleep(1)
        snap_now = __snapshoot()
        for net_name,speed in nets.items():
            print("speed:",speed)
            recv_prev = snap_prev[net_name]
            recv_now = snap_now[net_name]
            rate = (recv_now-recv_prev)/(speed*1024*1024/8.)
            print('name:%s,rate:%.2f%%' % (net_name,rate*100))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值