33# Update by : https://github.com/cppla/ServerStatus
44# 支持Python版本:2.7 to 3.7
55# 支持操作系统: Linux, OSX, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures
6- # 时间: 20200401
6+ # 时间: 20200407
77# 说明: 默认情况下修改server和user就可以了。丢包率监测方向可以自定义,例如:CU = "www.facebook.com"。
88
99SERVER = "127.0.0.1"
3131import threading
3232
3333def get_uptime ():
34- f = open ('/proc/uptime' , 'r' )
35- uptime = f .readline ()
36- f .close ()
37- uptime = uptime .split ('.' , 2 )
38- time = int (uptime [0 ])
39- return int (time )
34+ with open ('/proc/uptime' , 'r' ) as f :
35+ uptime = f .readline ().split ('.' , 2 )
36+ return int (uptime [0 ])
4037
4138def get_memory ():
4239 re_parser = re .compile (r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB' )
@@ -61,12 +58,11 @@ def get_hdd():
6158 return int (size ), int (used )
6259
6360def get_time ():
64- stat_file = open ("/proc/stat" , "r" )
65- time_list = stat_file .readline ().split (' ' )[2 :6 ]
66- stat_file .close ()
67- for i in range (len (time_list )) :
68- time_list [i ] = int (time_list [i ])
69- return time_list
61+ with open ("/proc/stat" , "r" ) as f :
62+ time_list = f .readline ().split (' ' )[2 :6 ]
63+ for i in range (len (time_list )) :
64+ time_list [i ] = int (time_list [i ])
65+ return time_list
7066
7167def delta_time ():
7268 x = get_time ()
@@ -84,10 +80,23 @@ def get_cpu():
8480 result = 100 - (t [len (t )- 1 ]* 100.00 / st )
8581 return round (result , 1 )
8682
83+ traffic_clock = time .time ()
84+ traffic_diff = 0
85+ def TCLOCK (func ):
86+ def wrapper (* args , ** kwargs ):
87+ global traffic_clock , traffic_diff
88+ now_clock = time .time ()
89+ traffic_diff = now_clock - traffic_clock
90+ traffic_clock = now_clock
91+ return func (* args , ** kwargs )
92+ return wrapper
93+
8794class Traffic :
8895 def __init__ (self ):
8996 self .rx = collections .deque (maxlen = 10 )
9097 self .tx = collections .deque (maxlen = 10 )
98+
99+ @TCLOCK
91100 def get (self ):
92101 f = open ('/proc/net/dev' , 'r' )
93102 net_dev = f .readlines ()
@@ -114,8 +123,8 @@ def get(self):
114123 avgrx += self .rx [x + 1 ] - self .rx [x ]
115124 avgtx += self .tx [x + 1 ] - self .tx [x ]
116125
117- avgrx = int (avgrx / l / INTERVAL )
118- avgtx = int (avgtx / l / INTERVAL )
126+ avgrx = int (avgrx / l / traffic_diff )
127+ avgtx = int (avgtx / l / traffic_diff )
119128
120129 return avgrx , avgtx
121130
@@ -278,7 +287,7 @@ def byte_str(object):
278287 INTERVAL = int (argc .split ('INTERVAL=' )[- 1 ])
279288 socket .setdefaulttimeout (30 )
280289 get_packetLostRate ()
281- while 1 :
290+ while True :
282291 try :
283292 print ("Connecting..." )
284293 s = socket .socket (socket .AF_INET , socket .SOCK_STREAM )
@@ -310,7 +319,7 @@ def byte_str(object):
310319
311320 traffic = Traffic ()
312321 traffic .get ()
313- while 1 :
322+ while True :
314323 CPU = get_cpu ()
315324 NetRx , NetTx = traffic .get ()
316325 NET_IN , NET_OUT = liuliang ()
0 commit comments