python檢測當前網卡流量信息,用於查看實時網速

能夠用來檢測是否有挖礦程序在運行的一個子條件spa

 1 # coding:utf-8
 2 __author__ = 'chenhuachao'
 3 import wmi  4 import time  5 import platform  6 
 7 def get_network_flow(os):  8     '''監控window平臺下網卡的實時的流量信息  9  經過當前總流量和一秒後的總流量的差值,來統計實時的網卡流量信息; 10  返回的流量單位是KB 11     '''
12     if os == "Windows": 13         c = wmi.WMI() 14         for interfacePerTcp in c.Win32_PerfRawData_Tcpip_TCPv4(): 15             sentflow = float(interfacePerTcp.SegmentsSentPersec)  #已發送的流量
16             receivedflow = float(interfacePerTcp.SegmentsReceivedPersec) #接收的流量
17             present_flow = sentflow+receivedflow    #算出當前的總流量
18         time.sleep(1) 19         for interfacePerTcp in c.Win32_PerfRawData_Tcpip_TCPv4(): 20            sentflow = float(interfacePerTcp.SegmentsSentPersec)  #已發送的流量
21            receivedflow = float(interfacePerTcp.SegmentsReceivedPersec) #接收的流量
22            per_last_present_flow = sentflow+receivedflow     #算出1秒後當前的總流量
23         present_network_flow = (per_last_present_flow - present_flow)/1024
24         print("當前流量爲:{0}KB".format("%.2f"%present_network_flow)) 25         return "%.2f"%present_network_flow 26 
27 if __name__ =="__main__": 28     os = platform.system() 29     while 1: 30         flow = get_network_flow(os) 31         print("{0}KB".format(flow))
相關文章
相關標籤/搜索