格式化代码,数据包增加丢包率packet

This commit is contained in:
ubuntu 2018-08-28 17:59:37 +08:00
parent 46def9acb2
commit 1ecca6e444
2 changed files with 385 additions and 371 deletions

@ -2,7 +2,7 @@
# Update by : https://github.com/cppla/ServerStatus # Update by : https://github.com/cppla/ServerStatus
# 支持Python版本2.7 to 3.5 # 支持Python版本2.7 to 3.5
# 支持操作系统: Linux, OSX, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures # 支持操作系统: Linux, OSX, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures
# 时间: 20180312 # 时间: 20180828
SERVER = "127.0.0.1" SERVER = "127.0.0.1"
@ -22,93 +22,93 @@ import collections
import threading import threading
def get_uptime(): def get_uptime():
f = open('/proc/uptime', 'r') f = open('/proc/uptime', 'r')
uptime = f.readline() uptime = f.readline()
f.close() f.close()
uptime = uptime.split('.', 2) uptime = uptime.split('.', 2)
time = int(uptime[0]) time = int(uptime[0])
return int(time) return int(time)
def get_memory(): def get_memory():
re_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB') re_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB')
result = dict() result = dict()
for line in open('/proc/meminfo'): for line in open('/proc/meminfo'):
match = re_parser.match(line) match = re_parser.match(line)
if not match: if not match:
continue; continue;
key, value = match.groups(['key', 'value']) key, value = match.groups(['key', 'value'])
result[key] = int(value) result[key] = int(value)
MemTotal = float(result['MemTotal']) MemTotal = float(result['MemTotal'])
MemFree = float(result['MemFree']) MemFree = float(result['MemFree'])
Cached = float(result['Cached']) Cached = float(result['Cached'])
MemUsed = MemTotal - (Cached + MemFree) MemUsed = MemTotal - (Cached + MemFree)
SwapTotal = float(result['SwapTotal']) SwapTotal = float(result['SwapTotal'])
SwapFree = float(result['SwapFree']) SwapFree = float(result['SwapFree'])
return int(MemTotal), int(MemUsed), int(SwapTotal), int(SwapFree) return int(MemTotal), int(MemUsed), int(SwapTotal), int(SwapFree)
def get_hdd(): def get_hdd():
p = subprocess.check_output(['df', '-Tlm', '--total', '-t', 'ext4', '-t', 'ext3', '-t', 'ext2', '-t', 'reiserfs', '-t', 'jfs', '-t', 'ntfs', '-t', 'fat32', '-t', 'btrfs', '-t', 'fuseblk', '-t', 'zfs', '-t', 'simfs', '-t', 'xfs']).decode("Utf-8") p = subprocess.check_output(['df', '-Tlm', '--total', '-t', 'ext4', '-t', 'ext3', '-t', 'ext2', '-t', 'reiserfs', '-t', 'jfs', '-t', 'ntfs', '-t', 'fat32', '-t', 'btrfs', '-t', 'fuseblk', '-t', 'zfs', '-t', 'simfs', '-t', 'xfs']).decode("Utf-8")
total = p.splitlines()[-1] total = p.splitlines()[-1]
used = total.split()[3] used = total.split()[3]
size = total.split()[2] size = total.split()[2]
return int(size), int(used) return int(size), int(used)
def get_time(): def get_time():
stat_file = file("/proc/stat", "r") stat_file = file("/proc/stat", "r")
time_list = stat_file.readline().split(' ')[2:6] time_list = stat_file.readline().split(' ')[2:6]
stat_file.close() stat_file.close()
for i in range(len(time_list)) : for i in range(len(time_list)) :
time_list[i] = int(time_list[i]) time_list[i] = int(time_list[i])
return time_list return time_list
def delta_time(): def delta_time():
x = get_time() x = get_time()
time.sleep(INTERVAL) time.sleep(INTERVAL)
y = get_time() y = get_time()
for i in range(len(x)): for i in range(len(x)):
y[i]-=x[i] y[i]-=x[i]
return y return y
def get_cpu(): def get_cpu():
t = delta_time() t = delta_time()
st = sum(t) st = sum(t)
if st == 0: if st == 0:
st = 1 st = 1
result = 100-(t[len(t)-1]*100.00/st) result = 100-(t[len(t)-1]*100.00/st)
return round(result) return round(result)
class Traffic: class Traffic:
def __init__(self): def __init__(self):
self.rx = collections.deque(maxlen=10) self.rx = collections.deque(maxlen=10)
self.tx = collections.deque(maxlen=10) self.tx = collections.deque(maxlen=10)
def get(self): def get(self):
f = open('/proc/net/dev', 'r') f = open('/proc/net/dev', 'r')
net_dev = f.readlines() net_dev = f.readlines()
f.close() f.close()
avgrx = 0; avgtx = 0 avgrx = 0; avgtx = 0
for dev in net_dev[2:]: for dev in net_dev[2:]:
dev = dev.split(':') dev = dev.split(':')
if dev[0].strip() == "lo" or dev[0].find("tun") > -1 \ if dev[0].strip() == "lo" or dev[0].find("tun") > -1 \
or dev[0].find("docker") > -1 or dev[0].find("veth") > -1 \ or dev[0].find("docker") > -1 or dev[0].find("veth") > -1 \
or dev[0].find("br-") > -1: or dev[0].find("br-") > -1:
continue continue
dev = dev[1].split() dev = dev[1].split()
avgrx += int(dev[0]) avgrx += int(dev[0])
avgtx += int(dev[8]) avgtx += int(dev[8])
self.rx.append(avgrx) self.rx.append(avgrx)
self.tx.append(avgtx) self.tx.append(avgtx)
avgrx = 0; avgtx = 0 avgrx = 0; avgtx = 0
l = len(self.rx) l = len(self.rx)
for x in range(l - 1): for x in range(l - 1):
avgrx += self.rx[x+1] - self.rx[x] avgrx += self.rx[x+1] - self.rx[x]
avgtx += self.tx[x+1] - self.tx[x] avgtx += self.tx[x+1] - self.tx[x]
avgrx = int(avgrx / l / INTERVAL) avgrx = int(avgrx / l / INTERVAL)
avgtx = int(avgtx / l / INTERVAL) avgtx = int(avgtx / l / INTERVAL)
return avgrx, avgtx return avgrx, avgtx
def liuliang(): def liuliang():
NET_IN = 0 NET_IN = 0
@ -118,9 +118,9 @@ def liuliang():
netinfo = re.findall('([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)', line) netinfo = re.findall('([^\s]+):[\s]{0,}(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)', line)
if netinfo: if netinfo:
if netinfo[0][0] == 'lo' or 'tun' in netinfo[0][0] \ if netinfo[0][0] == 'lo' or 'tun' in netinfo[0][0] \
or 'docker' in netinfo[0][0] or 'veth' in netinfo[0][0] \ or 'docker' in netinfo[0][0] or 'veth' in netinfo[0][0] \
or 'br-' in netinfo[0][0] \ or 'br-' in netinfo[0][0] \
or netinfo[0][1]=='0' or netinfo[0][9]=='0': or netinfo[0][1]=='0' or netinfo[0][9]=='0':
continue continue
else: else:
NET_IN += int(netinfo[0][1]) NET_IN += int(netinfo[0][1])
@ -128,35 +128,39 @@ def liuliang():
return NET_IN, NET_OUT return NET_IN, NET_OUT
def ip_status(): def ip_status():
object_check = ['www.10010.com', 'www.189.cn', 'www.10086.cn'] object_check = ['www.10010.com', 'www.189.cn', 'www.10086.cn']
ip_check = 0 ip_check = 0
for i in object_check: for i in object_check:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1) s.settimeout(1)
try: try:
s.connect((i, 80)) s.connect((i, 80))
except: except:
ip_check += 1 ip_check += 1
s.close() s.close()
del s del s
if ip_check >= 2: if ip_check >= 2:
return False return False
else: else:
return True return True
def get_network(ip_version): def get_network(ip_version):
if(ip_version == 4): if(ip_version == 4):
HOST = "ipv4.google.com" HOST = "ipv4.google.com"
elif(ip_version == 6): elif(ip_version == 6):
HOST = "ipv6.google.com" HOST = "ipv6.google.com"
try: try:
s = socket.create_connection((HOST, 80), 2) s = socket.create_connection((HOST, 80), 2)
return True return True
except: except:
pass pass
return False return False
lostRate = {} lostRate = {
'10010': 0.0,
'189': 0.0,
'10086': 0.0
}
def _ping_thread(host, mark): def _ping_thread(host, mark):
output = os.popen('ping -O %s &' % host) output = os.popen('ping -O %s &' % host)
lostCount = 0 lostCount = 0
@ -175,33 +179,33 @@ def _ping_thread(host, mark):
startTime = endTime startTime = endTime
def get_packetLostRate(): def get_packetLostRate():
t1 = threading.Thread( t1 = threading.Thread(
target=_ping_thread, target=_ping_thread,
kwargs={ kwargs={
'host': 'www.10010.com', 'host': 'www.10010.com',
'mark': '10010' 'mark': '10010'
} }
) )
t2 = threading.Thread( t2 = threading.Thread(
target=_ping_thread, target=_ping_thread,
kwargs={ kwargs={
'host': 'www.189.cn', 'host': 'www.189.cn',
'mark': '189' 'mark': '189'
} }
) )
t3 = threading.Thread( t3 = threading.Thread(
target=_ping_thread, target=_ping_thread,
kwargs={ kwargs={
'host': 'bj.10086.cn', 'host': 'bj.10086.cn',
'mark': '10086' 'mark': '10086'
} }
) )
t1.setDaemon(True) t1.setDaemon(True)
t2.setDaemon(True) t2.setDaemon(True)
t3.setDaemon(True) t3.setDaemon(True)
t1.start() t1.start()
t2.start() t2.start()
t3.start() t3.start()
if __name__ == '__main__': if __name__ == '__main__':
for argc in sys.argv: for argc in sys.argv:
@ -217,80 +221,83 @@ if __name__ == '__main__':
INTERVAL = int(argc.split('INTERVAL=')[-1]) INTERVAL = int(argc.split('INTERVAL=')[-1])
socket.setdefaulttimeout(30) socket.setdefaulttimeout(30)
while 1: while 1:
try: try:
print("Connecting...") print("Connecting...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER, PORT)) s.connect((SERVER, PORT))
data = s.recv(1024) data = s.recv(1024)
if data.find("Authentication required") > -1: if data.find("Authentication required") > -1:
s.send(USER + ':' + PASSWORD + '\n') s.send(USER + ':' + PASSWORD + '\n')
data = s.recv(1024) data = s.recv(1024)
if data.find("Authentication successful") < 0: if data.find("Authentication successful") < 0:
print(data) print(data)
raise socket.error raise socket.error
else: else:
print(data) print(data)
raise socket.error raise socket.error
print(data) print(data)
data = s.recv(1024) data = s.recv(1024)
print(data) print(data)
timer = 0 timer = 0
check_ip = 0 check_ip = 0
if data.find("IPv4") > -1: if data.find("IPv4") > -1:
check_ip = 6 check_ip = 6
elif data.find("IPv6") > -1: elif data.find("IPv6") > -1:
check_ip = 4 check_ip = 4
else: else:
print(data) print(data)
raise socket.error raise socket.error
traffic = Traffic() traffic = Traffic()
traffic.get() traffic.get()
while 1: while 1:
CPU = get_cpu() CPU = get_cpu()
NetRx, NetTx = traffic.get() NetRx, NetTx = traffic.get()
NET_IN, NET_OUT = liuliang() NET_IN, NET_OUT = liuliang()
Uptime = get_uptime() Uptime = get_uptime()
Load_1, Load_5, Load_15 = os.getloadavg() Load_1, Load_5, Load_15 = os.getloadavg()
MemoryTotal, MemoryUsed, SwapTotal, SwapFree = get_memory() MemoryTotal, MemoryUsed, SwapTotal, SwapFree = get_memory()
HDDTotal, HDDUsed = get_hdd() HDDTotal, HDDUsed = get_hdd()
IP_STATUS = ip_status() IP_STATUS = ip_status()
array = {} array = {}
if not timer: if not timer:
array['online' + str(check_ip)] = get_network(check_ip) array['online' + str(check_ip)] = get_network(check_ip)
timer = 10 timer = 10
else: else:
timer -= 1*INTERVAL timer -= 1*INTERVAL
array['uptime'] = Uptime array['uptime'] = Uptime
array['load_1'] = Load_1 array['load_1'] = Load_1
array['load_5'] = Load_5 array['load_5'] = Load_5
array['load_15'] = Load_15 array['load_15'] = Load_15
array['memory_total'] = MemoryTotal array['memory_total'] = MemoryTotal
array['memory_used'] = MemoryUsed array['memory_used'] = MemoryUsed
array['swap_total'] = SwapTotal array['swap_total'] = SwapTotal
array['swap_used'] = SwapTotal - SwapFree array['swap_used'] = SwapTotal - SwapFree
array['hdd_total'] = HDDTotal array['hdd_total'] = HDDTotal
array['hdd_used'] = HDDUsed array['hdd_used'] = HDDUsed
array['cpu'] = CPU array['cpu'] = CPU
array['network_rx'] = NetRx array['network_rx'] = NetRx
array['network_tx'] = NetTx array['network_tx'] = NetTx
array['network_in'] = NET_IN array['network_in'] = NET_IN
array['network_out'] = NET_OUT array['network_out'] = NET_OUT
array['ip_status'] = IP_STATUS array['ip_status'] = IP_STATUS
array['ping_10010'] = lostRate.get('10010') * 100
array['ping_189'] = lostRate.get('189') * 100
array['ping_10086'] = lostRate.get('10086') * 100
s.send("update " + json.dumps(array) + "\n") s.send("update " + json.dumps(array) + "\n")
except KeyboardInterrupt: except KeyboardInterrupt:
raise raise
except socket.error: except socket.error:
print("Disconnected...") print("Disconnected...")
# keep on trying after a disconnect # keep on trying after a disconnect
s.close() s.close()
time.sleep(3) time.sleep(3)
except Exception as e: except Exception as e:
print("Caught Exception:", e) print("Caught Exception:", e)
s.close() s.close()
time.sleep(3) time.sleep(3)

@ -3,7 +3,7 @@
# 依赖于psutil跨平台库 # 依赖于psutil跨平台库
# 支持Python版本2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version) # 支持Python版本2.6 to 3.5 (users of Python 2.4 and 2.5 may use 2.1.3 version)
# 支持操作系统: Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures # 支持操作系统: Linux, Windows, OSX, Sun Solaris, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures
# 时间: 20180312 # 时间: 20180828
SERVER = "127.0.0.1" SERVER = "127.0.0.1"
PORT = 35601 PORT = 35601
@ -22,64 +22,64 @@ import sys
import threading import threading
def get_uptime(): def get_uptime():
return int(time.time() - psutil.boot_time()) return int(time.time() - psutil.boot_time())
def get_memory(): def get_memory():
Mem = psutil.virtual_memory() Mem = psutil.virtual_memory()
try: try:
MemUsed = Mem.total - (Mem.cached + Mem.free) MemUsed = Mem.total - (Mem.cached + Mem.free)
except: except:
MemUsed = Mem.total - Mem.free MemUsed = Mem.total - Mem.free
return int(Mem.total/1024.0), int(MemUsed/1024.0) return int(Mem.total/1024.0), int(MemUsed/1024.0)
def get_swap(): def get_swap():
Mem = psutil.swap_memory() Mem = psutil.swap_memory()
return int(Mem.total/1024.0), int(Mem.used/1024.0) return int(Mem.total/1024.0), int(Mem.used/1024.0)
def get_hdd(): def get_hdd():
valid_fs = [ "ext4", "ext3", "ext2", "reiserfs", "jfs", "btrfs", "fuseblk", "zfs", "simfs", "ntfs", "fat32", "exfat", "xfs" ] valid_fs = [ "ext4", "ext3", "ext2", "reiserfs", "jfs", "btrfs", "fuseblk", "zfs", "simfs", "ntfs", "fat32", "exfat", "xfs" ]
disks = dict() disks = dict()
size = 0 size = 0
used = 0 used = 0
for disk in psutil.disk_partitions(): for disk in psutil.disk_partitions():
if not disk.device in disks and disk.fstype.lower() in valid_fs: if not disk.device in disks and disk.fstype.lower() in valid_fs:
disks[disk.device] = disk.mountpoint disks[disk.device] = disk.mountpoint
for disk in disks.itervalues(): for disk in disks.itervalues():
usage = psutil.disk_usage(disk) usage = psutil.disk_usage(disk)
size += usage.total size += usage.total
used += usage.used used += usage.used
return int(size/1024.0/1024.0), int(used/1024.0/1024.0) return int(size/1024.0/1024.0), int(used/1024.0/1024.0)
def get_cpu(): def get_cpu():
return psutil.cpu_percent(interval=INTERVAL) return psutil.cpu_percent(interval=INTERVAL)
class Traffic: class Traffic:
def __init__(self): def __init__(self):
self.rx = collections.deque(maxlen=10) self.rx = collections.deque(maxlen=10)
self.tx = collections.deque(maxlen=10) self.tx = collections.deque(maxlen=10)
def get(self): def get(self):
avgrx = 0; avgtx = 0 avgrx = 0; avgtx = 0
for name, stats in psutil.net_io_counters(pernic=True).iteritems(): for name, stats in psutil.net_io_counters(pernic=True).iteritems():
if name == "lo" or name.find("tun") > -1 \ if name == "lo" or name.find("tun") > -1 \
or name.find("docker") > -1 or name.find("veth") > -1 \ or name.find("docker") > -1 or name.find("veth") > -1 \
or name.find("br-") > -1: or name.find("br-") > -1:
continue continue
avgrx += stats.bytes_recv avgrx += stats.bytes_recv
avgtx += stats.bytes_sent avgtx += stats.bytes_sent
self.rx.append(avgrx) self.rx.append(avgrx)
self.tx.append(avgtx) self.tx.append(avgtx)
avgrx = 0; avgtx = 0 avgrx = 0; avgtx = 0
l = len(self.rx) l = len(self.rx)
for x in range(l - 1): for x in range(l - 1):
avgrx += self.rx[x+1] - self.rx[x] avgrx += self.rx[x+1] - self.rx[x]
avgtx += self.tx[x+1] - self.tx[x] avgtx += self.tx[x+1] - self.tx[x]
avgrx = int(avgrx / l / INTERVAL) avgrx = int(avgrx / l / INTERVAL)
avgtx = int(avgtx / l / INTERVAL) avgtx = int(avgtx / l / INTERVAL)
return avgrx, avgtx return avgrx, avgtx
def liuliang(): def liuliang():
NET_IN = 0 NET_IN = 0
@ -87,8 +87,8 @@ def liuliang():
net = psutil.net_io_counters(pernic=True) net = psutil.net_io_counters(pernic=True)
for k, v in net.items(): for k, v in net.items():
if k == 'lo' or 'tun' in k \ if k == 'lo' or 'tun' in k \
or 'br-' in k \ or 'br-' in k \
or 'docker' in k or 'veth' in k: or 'docker' in k or 'veth' in k:
continue continue
else: else:
NET_IN += v[1] NET_IN += v[1]
@ -96,35 +96,39 @@ def liuliang():
return NET_IN, NET_OUT return NET_IN, NET_OUT
def ip_status(): def ip_status():
object_check = ['www.10010.com', 'www.189.cn', 'www.10086.cn'] object_check = ['www.10010.com', 'www.189.cn', 'www.10086.cn']
ip_check = 0 ip_check = 0
for i in object_check: for i in object_check:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(1) s.settimeout(1)
try: try:
s.connect((i, 80)) s.connect((i, 80))
except: except:
ip_check += 1 ip_check += 1
s.close() s.close()
del s del s
if ip_check >= 2: if ip_check >= 2:
return False return False
else: else:
return True return True
def get_network(ip_version): def get_network(ip_version):
if(ip_version == 4): if(ip_version == 4):
HOST = "ipv4.google.com" HOST = "ipv4.google.com"
elif(ip_version == 6): elif(ip_version == 6):
HOST = "ipv6.google.com" HOST = "ipv6.google.com"
try: try:
s = socket.create_connection((HOST, 80), 2) s = socket.create_connection((HOST, 80), 2)
return True return True
except: except:
pass pass
return False return False
lostRate = {} lostRate = {
'10010': 0.0,
'189': 0.0,
'10086': 0.0
}
def _ping_thread(host, mark): def _ping_thread(host, mark):
output = os.popen('ping -O %s &' % host if 'linux' in sys.platform else 'ping %s -t &' % host) output = os.popen('ping -O %s &' % host if 'linux' in sys.platform else 'ping %s -t &' % host)
lostCount = 0 lostCount = 0
@ -144,33 +148,33 @@ def _ping_thread(host, mark):
startTime = endTime startTime = endTime
def get_packetLostRate(): def get_packetLostRate():
t1 = threading.Thread( t1 = threading.Thread(
target=_ping_thread, target=_ping_thread,
kwargs={ kwargs={
'host': 'www.10010.com', 'host': 'www.10010.com',
'mark': '10010' 'mark': '10010'
} }
) )
t2 = threading.Thread( t2 = threading.Thread(
target=_ping_thread, target=_ping_thread,
kwargs={ kwargs={
'host': 'www.189.cn', 'host': 'www.189.cn',
'mark': '189' 'mark': '189'
} }
) )
t3 = threading.Thread( t3 = threading.Thread(
target=_ping_thread, target=_ping_thread,
kwargs={ kwargs={
'host': 'bj.10086.cn', 'host': 'bj.10086.cn',
'mark': '10086' 'mark': '10086'
} }
) )
t1.setDaemon(True) t1.setDaemon(True)
t2.setDaemon(True) t2.setDaemon(True)
t3.setDaemon(True) t3.setDaemon(True)
t1.start() t1.start()
t2.start() t2.start()
t3.start() t3.start()
if __name__ == '__main__': if __name__ == '__main__':
for argc in sys.argv: for argc in sys.argv:
@ -186,81 +190,84 @@ if __name__ == '__main__':
INTERVAL = int(argc.split('INTERVAL=')[-1]) INTERVAL = int(argc.split('INTERVAL=')[-1])
socket.setdefaulttimeout(30) socket.setdefaulttimeout(30)
while 1: while 1:
try: try:
print("Connecting...") print("Connecting...")
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((SERVER, PORT)) s.connect((SERVER, PORT))
data = s.recv(1024) data = s.recv(1024)
if data.find("Authentication required") > -1: if data.find("Authentication required") > -1:
s.send(USER + ':' + PASSWORD + '\n') s.send(USER + ':' + PASSWORD + '\n')
data = s.recv(1024) data = s.recv(1024)
if data.find("Authentication successful") < 0: if data.find("Authentication successful") < 0:
print(data) print(data)
raise socket.error raise socket.error
else: else:
print(data) print(data)
raise socket.error raise socket.error
print(data) print(data)
data = s.recv(1024) data = s.recv(1024)
print(data) print(data)
timer = 0 timer = 0
check_ip = 0 check_ip = 0
if data.find("IPv4") > -1: if data.find("IPv4") > -1:
check_ip = 6 check_ip = 6
elif data.find("IPv6") > -1: elif data.find("IPv6") > -1:
check_ip = 4 check_ip = 4
else: else:
print(data) print(data)
raise socket.error raise socket.error
traffic = Traffic() traffic = Traffic()
traffic.get() traffic.get()
while 1: while 1:
CPU = get_cpu() CPU = get_cpu()
NetRx, NetTx = traffic.get() NetRx, NetTx = traffic.get()
NET_IN, NET_OUT = liuliang() NET_IN, NET_OUT = liuliang()
Uptime = get_uptime() Uptime = get_uptime()
Load_1, Load_5, Load_15 = os.getloadavg() if 'linux' in sys.platform else (0.0, 0.0, 0.0) Load_1, Load_5, Load_15 = os.getloadavg() if 'linux' in sys.platform else (0.0, 0.0, 0.0)
MemoryTotal, MemoryUsed = get_memory() MemoryTotal, MemoryUsed = get_memory()
SwapTotal, SwapUsed = get_swap() SwapTotal, SwapUsed = get_swap()
HDDTotal, HDDUsed = get_hdd() HDDTotal, HDDUsed = get_hdd()
IP_STATUS = ip_status() IP_STATUS = ip_status()
array = {} array = {}
if not timer: if not timer:
array['online' + str(check_ip)] = get_network(check_ip) array['online' + str(check_ip)] = get_network(check_ip)
timer = 10 timer = 10
else: else:
timer -= 1*INTERVAL timer -= 1*INTERVAL
array['uptime'] = Uptime array['uptime'] = Uptime
array['load_1'] = Load_1 array['load_1'] = Load_1
array['load_5'] = Load_5 array['load_5'] = Load_5
array['load_15'] = Load_15 array['load_15'] = Load_15
array['memory_total'] = MemoryTotal array['memory_total'] = MemoryTotal
array['memory_used'] = MemoryUsed array['memory_used'] = MemoryUsed
array['swap_total'] = SwapTotal array['swap_total'] = SwapTotal
array['swap_used'] = SwapUsed array['swap_used'] = SwapUsed
array['hdd_total'] = HDDTotal array['hdd_total'] = HDDTotal
array['hdd_used'] = HDDUsed array['hdd_used'] = HDDUsed
array['cpu'] = CPU array['cpu'] = CPU
array['network_rx'] = NetRx array['network_rx'] = NetRx
array['network_tx'] = NetTx array['network_tx'] = NetTx
array['network_in'] = NET_IN array['network_in'] = NET_IN
array['network_out'] = NET_OUT array['network_out'] = NET_OUT
array['ip_status'] = IP_STATUS array['ip_status'] = IP_STATUS
array['ping_10010'] = lostRate.get('10010') * 100
array['ping_189'] = lostRate.get('189') * 100
array['ping_10086'] = lostRate.get('10086') * 100
s.send("update " + json.dumps(array) + "\n") s.send("update " + json.dumps(array) + "\n")
except KeyboardInterrupt: except KeyboardInterrupt:
raise raise
except socket.error: except socket.error:
print("Disconnected...") print("Disconnected...")
# keep on trying after a disconnect # keep on trying after a disconnect
s.close() s.close()
time.sleep(3) time.sleep(3)
except Exception as e: except Exception as e:
print("Caught Exception:", e) print("Caught Exception:", e)
s.close() s.close()
time.sleep(3) time.sleep(3)