resource_monitoring_client.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import requests
  2. import json
  3. import psutil
  4. import time
  5. def get_ip_address():
  6. return "10.181.7.236"
  7. def get_system_uptime():
  8. return int(time.time()-psutil.boot_time() )
  9. def get_cpu_info():
  10. cpu_cores = psutil.cpu_count(logical=False) # 物理CPU核心数
  11. cpu_count = psutil.cpu_count() # 总CPU核心数(包括逻辑CPU)
  12. cpu_freq = psutil.cpu_freq().current # CPU频率
  13. return {
  14. 'cpu_cores': cpu_cores,
  15. 'cpu_count': cpu_count,
  16. 'cpu_freq': cpu_freq,
  17. }
  18. def get_memory_info():
  19. memory = psutil.virtual_memory()
  20. return {
  21. 'total_memory': memory.total,
  22. 'memory_usage': memory.percent,
  23. }
  24. def get_disk_info(path='/'):
  25. disk = psutil.disk_usage(path)
  26. disk_io = psutil.disk_io_counters()
  27. return {
  28. 'disk_total':disk.total,
  29. 'disk_usage': disk.percent,
  30. 'disk_read_speed': disk_io.read_bytes / (1024 ** 2), # 转换为MB/s
  31. 'disk_write_speed': disk_io.write_bytes / (1024 ** 2), # 转换为MB/s
  32. }
  33. def get_cpu_usage():
  34. return psutil.cpu_percent(interval=1)
  35. def monitor_system(interval=60):
  36. url = "http://10.181.7.236:9988/api/resource/monitoring"
  37. headers = {
  38. 'Content-Type': 'application/json'
  39. }
  40. while 1:
  41. payload = json.dumps({
  42. "system_ip" : get_ip_address(),
  43. "system_uptime" : get_system_uptime(),
  44. 'cpu_cores' : get_cpu_info()['cpu_cores'],
  45. 'cpu_count' : get_cpu_info()['cpu_count'],
  46. 'cpu_freq' : get_cpu_info()['cpu_freq'],
  47. 'cpu_usage' : get_cpu_usage(),
  48. 'memory_total' : get_memory_info()['total_memory']/(1024 ** 3),
  49. 'memory_usage' : get_memory_info()['memory_usage'],
  50. 'disk1_name' : '/',
  51. 'disk1_total' : get_disk_info()['disk_total']/(1024 ** 3),
  52. 'disk1_usage' : get_disk_info()['disk_usage'],
  53. 'disk1_read_speed' : get_disk_info()['disk_read_speed']/(1024 ** 2),
  54. 'disk1_write_speed' : get_disk_info()['disk_write_speed']/(1024 ** 2),
  55. 'disk2_name' : '/data',
  56. 'disk2_total' : get_disk_info('/data')['disk_total']/(1024 ** 3),
  57. 'disk2_usage' : get_disk_info('/data')['disk_usage'],
  58. 'disk2_read_speed' : get_disk_info('/data')['disk_read_speed']/(1024 ** 2),
  59. 'disk2_write_speed' : get_disk_info('/data')['disk_write_speed']/(1024 ** 2)
  60. })
  61. response = requests.request("POST", url, headers=headers, data=payload)
  62. print(response.text)
  63. print(payload)
  64. time.sleep(interval)
  65. if __name__ == "__main__":
  66. monitor_system()