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.

301 lines
6.8 KiB

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