client-linux.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # Update by : https://github.com/cppla/ServerStatus
  4. # 支持Python版本:2.7 to 3.7
  5. # 支持操作系统: Linux, OSX, FreeBSD, OpenBSD and NetBSD, both 32-bit and 64-bit architectures
  6. # 时间: 20200407
  7. # 说明: 默认情况下修改server和user就可以了。丢包率监测方向可以自定义,例如:CU = "www.facebook.com"。
  8. SERVER = "127.0.0.1"
  9. USER = "s01"
  10. PORT = 35601
  11. PASSWORD = "USER_DEFAULT_PASSWORD"
  12. INTERVAL = 1
  13. PORBEPORT = 80
  14. CU = "cu.tz.cloudcpp.com"
  15. CT = "ct.tz.cloudcpp.com"
  16. CM = "cm.tz.cloudcpp.com"
  17. import socket
  18. import time
  19. import timeit
  20. import re
  21. import os
  22. import sys
  23. import json
  24. import subprocess
  25. import threading
  26. def get_uptime():
  27. with open('/proc/uptime', 'r') as f:
  28. uptime = f.readline().split('.', 2)
  29. return int(uptime[0])
  30. def get_memory():
  31. re_parser = re.compile(r'^(?P<key>\S*):\s*(?P<value>\d*)\s*kB')
  32. result = dict()
  33. for line in open('/proc/meminfo'):
  34. match = re_parser.match(line)
  35. if not match:
  36. continue
  37. key, value = match.groups(['key', 'value'])
  38. result[key] = int(value)
  39. MemTotal = float(result['MemTotal'])
  40. MemUsed = MemTotal-float(result['MemFree'])-float(result['Buffers'])-float(result['Cached'])-float(result['SReclaimable'])
  41. SwapTotal = float(result['SwapTotal'])
  42. SwapFree = float(result['SwapFree'])
  43. return int(MemTotal), int(MemUsed), int(SwapTotal), int(SwapFree)
  44. def get_hdd():
  45. 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")
  46. total = p.splitlines()[-1]
  47. used = total.split()[3]
  48. size = total.split()[2]
  49. return int(size), int(used)
  50. def get_time():
  51. with open("/proc/stat", "r") as f:
  52. time_list = f.readline().split(' ')[2:6]
  53. for i in range(len(time_list)) :
  54. time_list[i] = int(time_list[i])
  55. return time_list
  56. def delta_time():
  57. x = get_time()
  58. time.sleep(INTERVAL)
  59. y = get_time()
  60. for i in range(len(x)):
  61. y[i]-=x[i]
  62. return y
  63. def get_cpu():
  64. t = delta_time()
  65. st = sum(t)
  66. if st == 0:
  67. st = 1
  68. result = 100-(t[len(t)-1]*100.00/st)
  69. return round(result, 1)
  70. def liuliang():
  71. NET_IN = 0
  72. NET_OUT = 0
  73. with open('/proc/net/dev') as f:
  74. for line in f.readlines():
  75. 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)
  76. if netinfo:
  77. if netinfo[0][0] == 'lo' or 'tun' in netinfo[0][0] \
  78. or 'docker' in netinfo[0][0] or 'veth' in netinfo[0][0] \
  79. or 'br-' in netinfo[0][0] or 'vmbr' in netinfo[0][0] \
  80. or 'vnet' in netinfo[0][0] or 'kube' in netinfo[0][0] \
  81. or netinfo[0][1]=='0' or netinfo[0][9]=='0':
  82. continue
  83. else:
  84. NET_IN += int(netinfo[0][1])
  85. NET_OUT += int(netinfo[0][9])
  86. return NET_IN, NET_OUT
  87. def tupd():
  88. '''
  89. tcp, udp, process, thread count: for view ddcc attack , then send warning
  90. :return:
  91. '''
  92. s = subprocess.check_output("ss -t|wc -l", shell=True)
  93. t = int(s[:-1])-1
  94. s = subprocess.check_output("ss -u|wc -l", shell=True)
  95. u = int(s[:-1])-1
  96. s = subprocess.check_output("ps -ef|wc -l", shell=True)
  97. p = int(s[:-1])-2
  98. s = subprocess.check_output("ps -eLf|wc -l", shell=True)
  99. d = int(s[:-1])-2
  100. return t,u,p,d
  101. def ip_status():
  102. ip_check = 0
  103. for i in [CU, CT, CM]:
  104. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  105. s.settimeout(1)
  106. try:
  107. s.connect((i, PORBEPORT))
  108. except:
  109. ip_check += 1
  110. s.close()
  111. del s
  112. if ip_check >= 2:
  113. return False
  114. else:
  115. return True
  116. def get_network(ip_version):
  117. if(ip_version == 4):
  118. HOST = "ipv4.google.com"
  119. elif(ip_version == 6):
  120. HOST = "ipv6.google.com"
  121. try:
  122. s = socket.create_connection((HOST, 80), 2)
  123. s.close()
  124. return True
  125. except:
  126. return False
  127. lostRate = {
  128. '10010': 0.0,
  129. '189': 0.0,
  130. '10086': 0.0
  131. }
  132. pingTime = {
  133. '10010': 0,
  134. '189': 0,
  135. '10086': 0
  136. }
  137. netSpeed = {
  138. 'netrx': 0.0,
  139. 'nettx': 0.0,
  140. 'clock': 0.0,
  141. 'diff': 0.0,
  142. 'avgrx': 0,
  143. 'avgtx': 0
  144. }
  145. def _ping_thread(host, mark, port):
  146. lostPacket = 0
  147. allPacket = 0
  148. startTime = time.time()
  149. while True:
  150. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  151. s.settimeout(1)
  152. try:
  153. b = timeit.default_timer()
  154. s.connect((host, port))
  155. pingTime[mark] = int((timeit.default_timer()-b)*1000)
  156. except:
  157. lostPacket += 1
  158. finally:
  159. allPacket += 1
  160. s.close()
  161. if allPacket > 100:
  162. lostRate[mark] = float(lostPacket) / allPacket
  163. endTime = time.time()
  164. if endTime - startTime > 3600:
  165. lostPacket = 0
  166. allPacket = 0
  167. startTime = endTime
  168. time.sleep(INTERVAL)
  169. def _net_speed():
  170. while True:
  171. with open("/proc/net/dev", "r") as f:
  172. net_dev = f.readlines()
  173. avgrx = 0
  174. avgtx = 0
  175. for dev in net_dev[2:]:
  176. dev = dev.split(':')
  177. if "lo" in dev[0] or "tun" in dev[0] \
  178. or "docker" in dev[0] or "veth" in dev[0] \
  179. or "br-" in dev[0] or "vmbr" in dev[0] \
  180. or "vnet" in dev[0] or "kube" in dev[0]:
  181. continue
  182. dev = dev[1].split()
  183. avgrx += int(dev[0])
  184. avgtx += int(dev[8])
  185. now_clock = time.time()
  186. netSpeed["diff"] = now_clock - netSpeed["clock"]
  187. netSpeed["clock"] = now_clock
  188. netSpeed["netrx"] = int((avgrx - netSpeed["avgrx"]) / netSpeed["diff"])
  189. netSpeed["nettx"] = int((avgtx - netSpeed["avgtx"]) / netSpeed["diff"])
  190. netSpeed["avgrx"] = avgrx
  191. netSpeed["avgtx"] = avgtx
  192. time.sleep(INTERVAL)
  193. def get_realtime_date():
  194. t1 = threading.Thread(
  195. target=_ping_thread,
  196. kwargs={
  197. 'host': CU,
  198. 'mark': '10010',
  199. 'port': PORBEPORT
  200. }
  201. )
  202. t2 = threading.Thread(
  203. target=_ping_thread,
  204. kwargs={
  205. 'host': CT,
  206. 'mark': '189',
  207. 'port': PORBEPORT
  208. }
  209. )
  210. t3 = threading.Thread(
  211. target=_ping_thread,
  212. kwargs={
  213. 'host': CM,
  214. 'mark': '10086',
  215. 'port': PORBEPORT
  216. }
  217. )
  218. t4 = threading.Thread(
  219. target=_net_speed,
  220. )
  221. t1.setDaemon(True)
  222. t2.setDaemon(True)
  223. t3.setDaemon(True)
  224. t4.setDaemon(True)
  225. t1.start()
  226. t2.start()
  227. t3.start()
  228. t4.start()
  229. def byte_str(object):
  230. '''
  231. bytes to str, str to bytes
  232. :param object:
  233. :return:
  234. '''
  235. if isinstance(object, str):
  236. return object.encode(encoding="utf-8")
  237. elif isinstance(object, bytes):
  238. return bytes.decode(object)
  239. else:
  240. print(type(object))
  241. if __name__ == '__main__':
  242. for argc in sys.argv:
  243. if 'SERVER' in argc:
  244. SERVER = argc.split('SERVER=')[-1]
  245. elif 'PORT' in argc:
  246. PORT = int(argc.split('PORT=')[-1])
  247. elif 'USER' in argc:
  248. USER = argc.split('USER=')[-1]
  249. elif 'PASSWORD' in argc:
  250. PASSWORD = argc.split('PASSWORD=')[-1]
  251. elif 'INTERVAL' in argc:
  252. INTERVAL = int(argc.split('INTERVAL=')[-1])
  253. socket.setdefaulttimeout(30)
  254. get_realtime_date()
  255. while True:
  256. try:
  257. print("Connecting...")
  258. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  259. s.connect((SERVER, PORT))
  260. data = byte_str(s.recv(1024))
  261. if data.find("Authentication required") > -1:
  262. s.send(byte_str(USER + ':' + PASSWORD + '\n'))
  263. data = byte_str(s.recv(1024))
  264. if data.find("Authentication successful") < 0:
  265. print(data)
  266. raise socket.error
  267. else:
  268. print(data)
  269. raise socket.error
  270. print(data)
  271. data = byte_str(s.recv(1024))
  272. print(data)
  273. timer = 0
  274. check_ip = 0
  275. if data.find("IPv4") > -1:
  276. check_ip = 6
  277. elif data.find("IPv6") > -1:
  278. check_ip = 4
  279. else:
  280. print(data)
  281. raise socket.error
  282. while True:
  283. CPU = get_cpu()
  284. NET_IN, NET_OUT = liuliang()
  285. Uptime = get_uptime()
  286. Load_1, Load_5, Load_15 = os.getloadavg()
  287. MemoryTotal, MemoryUsed, SwapTotal, SwapFree = get_memory()
  288. HDDTotal, HDDUsed = get_hdd()
  289. IP_STATUS = ip_status()
  290. array = {}
  291. if not timer:
  292. array['online' + str(check_ip)] = get_network(check_ip)
  293. timer = 10
  294. else:
  295. timer -= 1*INTERVAL
  296. array['uptime'] = Uptime
  297. array['load_1'] = Load_1
  298. array['load_5'] = Load_5
  299. array['load_15'] = Load_15
  300. array['memory_total'] = MemoryTotal
  301. array['memory_used'] = MemoryUsed
  302. array['swap_total'] = SwapTotal
  303. array['swap_used'] = SwapTotal - SwapFree
  304. array['hdd_total'] = HDDTotal
  305. array['hdd_used'] = HDDUsed
  306. array['cpu'] = CPU
  307. array['network_rx'] = netSpeed.get("netrx")
  308. array['network_tx'] = netSpeed.get("nettx")
  309. array['network_in'] = NET_IN
  310. array['network_out'] = NET_OUT
  311. array['ip_status'] = IP_STATUS
  312. array['ping_10010'] = lostRate.get('10010') * 100
  313. array['ping_189'] = lostRate.get('189') * 100
  314. array['ping_10086'] = lostRate.get('10086') * 100
  315. array['time_10010'] = pingTime.get('10010')
  316. array['time_189'] = pingTime.get('189')
  317. array['time_10086'] = pingTime.get('10086')
  318. array['tcp'], array['udp'], array['process'], array['thread'] = tupd()
  319. s.send(byte_str("update " + json.dumps(array) + "\n"))
  320. except KeyboardInterrupt:
  321. raise
  322. except socket.error:
  323. print("Disconnected...")
  324. # keep on trying after a disconnect
  325. s.close()
  326. time.sleep(3)
  327. except Exception as e:
  328. print("Caught Exception:", e)
  329. s.close()
  330. time.sleep(3)