You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

277 lines
6.6 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
  1. import os
  2. import platform
  3. import multiprocessing
  4. from datetime import timedelta
  5. import psutil
  6. import cpuinfo
  7. import uptime
  8. import platform
  9. import datetime
  10. # https://stackoverflow.com/questions/1094841/reusable-library-to-get-human-readable-version-of-file-size
  11. def sizeof_fmt(num, suffix=''):
  12. for unit in ['','K','M','G','T','P','E','Z']:
  13. if abs(num) < 1024.0:
  14. return f"{num:3.1f}{unit}{suffix}"
  15. num /= 1024.0
  16. return "{:3.1f}{}{}".format(num, 'Yi', suffix)
  17. def chunks(get, n):
  18. return [get[i:i + n] for i in range(0, len(get), n)]
  19. # win comp
  20. def get_uptime():
  21. """
  22. Get uptime
  23. """
  24. import uptime
  25. td = datetime.timedelta(seconds=round(uptime.uptime()))
  26. return str(td)
  27. def get_ipaddress():
  28. """
  29. Get the IP Address
  30. """
  31. data = []
  32. try:
  33. eth = os.popen("ip addr | grep LOWER_UP | awk '{print $2}'")
  34. iface = eth.read().strip().replace(':', '').split('\n')
  35. eth.close()
  36. del iface[0]
  37. for i in iface:
  38. pipe = os.popen(
  39. "ip addr show " + i + "| awk '{if ($2 == \"forever\"){!$2} else {print $2}}'")
  40. data1 = pipe.read().strip().split('\n')
  41. pipe.close()
  42. if len(data1) == 2:
  43. data1.append('unavailable')
  44. if len(data1) == 3:
  45. data1.append('unavailable')
  46. data1[0] = i
  47. data.append(data1)
  48. ips = {'interface': iface, 'itfip': data}
  49. data = ips
  50. except Exception as err:
  51. data = str(err)
  52. return data
  53. # win comp
  54. _cpu_info = None
  55. def get_cpus():
  56. """
  57. Get the number of CPUs and model/type
  58. """
  59. global _cpu_info
  60. if not _cpu_info:
  61. cpu_info = cpuinfo.get_cpu_info()
  62. _cpu_info = {"cpus":cpu_info["count"],"type": cpu_info["brand"]}
  63. return _cpu_info
  64. # win comp
  65. def get_users():
  66. """
  67. Get the current logged in users
  68. """
  69. return [[user.name,user.terminal,user.host] for user in psutil.users()]
  70. def get_traffic(request):
  71. """
  72. Get the traffic for the specified interface
  73. """
  74. try:
  75. pipe = os.popen(
  76. "cat /proc/net/dev |" + "grep " + request + "| awk '{print $1, $9}'")
  77. data = pipe.read().strip().split(':', 1)[-1]
  78. pipe.close()
  79. if not data[0].isdigit():
  80. pipe = os.popen(
  81. "cat /proc/net/dev |" + "grep " + request + "| awk '{print $2, $10}'")
  82. data = pipe.read().strip().split(':', 1)[-1]
  83. pipe.close()
  84. data = data.split()
  85. traffic_in = int(data[0])
  86. traffic_out = int(data[1])
  87. all_traffic = {'traffic_in': traffic_in, 'traffic_out': traffic_out}
  88. data = all_traffic
  89. except Exception as err:
  90. data = str(err)
  91. return data
  92. _platform = None
  93. def get_platform():
  94. """
  95. Get the OS name, hostname and kernel
  96. """
  97. global _platform
  98. if not _platform:
  99. _platform = {"kernel":platform.version(),"hostname":platform.node(),"osname":platform.platform(terse=True)}
  100. return _platform
  101. # win comp
  102. def get_disk():
  103. """
  104. Get disk usage
  105. """
  106. data = []
  107. for disk in psutil.disk_partitions():
  108. try:
  109. disk_usage = psutil.disk_usage(disk.mountpoint)
  110. data.append(
  111. [ disk.device,
  112. sizeof_fmt(disk_usage.total),
  113. sizeof_fmt(disk_usage.used),
  114. sizeof_fmt(disk_usage.free),
  115. "{}%".format(round(disk_usage.percent)),
  116. disk.mountpoint,
  117. ])
  118. except PermissionError:
  119. pass
  120. return data
  121. def get_disk_rw():
  122. """
  123. Get the disk reads and writes
  124. """
  125. try:
  126. pipe = os.popen(
  127. "cat /proc/partitions | grep -v 'major' | awk '{print $4}'")
  128. data = pipe.read().strip().split('\n')
  129. pipe.close()
  130. rws = []
  131. for i in data:
  132. if i.isalpha():
  133. pipe = os.popen(
  134. "cat /proc/diskstats | grep -w '" + i + "'|awk '{print $4, $8}'")
  135. rw = pipe.read().strip().split()
  136. pipe.close()
  137. rws.append([i, rw[0], rw[1]])
  138. if not rws:
  139. pipe = os.popen(
  140. "cat /proc/diskstats | grep -w '" + data[0] + "'|awk '{print $4, $8}'")
  141. rw = pipe.read().strip().split()
  142. pipe.close()
  143. rws.append([data[0], rw[0], rw[1]])
  144. data = rws
  145. except Exception as err:
  146. data = str(err)
  147. return data
  148. def get_mem():
  149. """
  150. Get memory usage
  151. """
  152. try:
  153. pipe = os.popen(
  154. "free -tm | " + "grep 'Mem' | " + "awk '{print $2,$4,$6,$7}'")
  155. data = pipe.read().strip().split()
  156. pipe.close()
  157. allmem = int(data[0])
  158. freemem = int(data[1])
  159. buffers = int(data[2])
  160. cachedmem = int(data[3])
  161. # Memory in buffers + cached is actually available, so we count it
  162. # as free. See http://www.linuxatemyram.com/ for details
  163. freemem += buffers + cachedmem
  164. percent = (100 - ((freemem * 100) / allmem))
  165. usage = (allmem - freemem)
  166. mem_usage = {'usage': usage, 'buffers': buffers, 'cached': cachedmem, 'free': freemem, 'percent': percent}
  167. data = mem_usage
  168. except Exception as err:
  169. data = str(err)
  170. return data
  171. def get_cpu_usage():
  172. """
  173. Get the CPU usage and running processes
  174. """
  175. try:
  176. pipe = os.popen("ps aux --sort -%cpu,-rss")
  177. data = pipe.read().strip().split('\n')
  178. pipe.close()
  179. usage = [i.split(None, 10) for i in data]
  180. del usage[0]
  181. total_usage = []
  182. for element in usage:
  183. usage_cpu = element[2]
  184. total_usage.append(usage_cpu)
  185. total_usage = sum(float(i) for i in total_usage)
  186. total_free = ((100 * int(get_cpus()['cpus'])) - float(total_usage))
  187. cpu_used = {'free': total_free, 'used':
  188. float(total_usage), 'all': usage}
  189. data = cpu_used
  190. except Exception as err:
  191. data = str(err)
  192. return data
  193. def get_load():
  194. """
  195. Get load average
  196. """
  197. try:
  198. data = os.getloadavg()[0]
  199. except Exception as err:
  200. data = "N/A"
  201. return data
  202. def get_netstat():
  203. """
  204. Get ports and applications
  205. """
  206. try:
  207. pipe = os.popen(
  208. "ss -tnp | grep ESTAB | awk '{print $4, $5}'| sed 's/::ffff://g' | awk -F: '{print $1, $2}' "
  209. "| awk 'NF > 0' | sort -n | uniq -c")
  210. data = pipe.read().strip().split('\n')
  211. pipe.close()
  212. data = [i.split(None, 4) for i in data]
  213. except Exception as err:
  214. data = str(err)
  215. return data