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))