сценарий сетевого мониторинга psutil - PullRequest
0 голосов
/ 26 мая 2020

Я пытаюсь создать сценарий для мониторинга основных c ресурсов сервера: - ЦП, ОЗУ, ДИСК и СЕТЬ ВХОДИТ И ВЫХОДИТ (в мегабайтах / сек c). К сожалению, пока работают части процессора, памяти и диска, сетевая функция всегда показывает 0,0 байта на входе или выходе, даже если есть реальный трафик c (yum update -y). Пожалуйста, помогите и имейте в виду, что я полный новичок в Python, это просто практический проект. Заранее благодарим.

Мы приветствуем любые предложения по оптимизации.

#!/usr/bin/env python3
#Module psutil needs to be installed via pip3 first.
#Python script to Monitor Server Resources.

import time
import psutil

cpu_thresh = 50.0
cpu_pct = psutil.cpu_percent(interval=1)

if cpu_pct >= cpu_thresh:
    print("CPU Warning, CPU at ",cpu_pct, "percent")

mem = psutil.virtual_memory()
mem_thresh = 1024 * 1024 * 1024 #500MB

if mem_thresh >= mem.available:
    print("Memory Usage Warning only", mem.available /1024 /1024, "MB available")

partition1 = '/'
disk1 = psutil.disk_usage(partition1)
disk_thresh = 85.0

if disk_thresh <= disk1[3]:
    print("Root volume usage warning", disk1[3], "% used")

def net_in(inf = "eth0"):   #change the inf variable according to the interface
  net_in_ps = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
  net_in_1 = net_in_ps.bytes_recv
  time.sleep(1)
  net_in_2 = net_in_ps.bytes_recv
  net_in_result = net_in_2 - net_in_1
  net_in_result_mbps = net_in_result /1024 /1024
  print(net_in_result_mbps)
  net_in_thresh = 1.5
  if net_in_result_mbps <= net_in_thresh:
      print("Network in Warning, NetSpeed at:", net_in_result_mbps, "mbps")

def net_out(inf = "eth0"):   #change the inf variable according to the interface
  net_out_ps = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
  net_out_1 = net_out_ps.bytes_sent
  time.sleep(1)
  net_out_2 = net_out_ps.bytes_sent
  net_out_result = net_out_2 - net_out_1
  net_out_result_mbps = net_out_result /1024 /1024
  print(net_out_result_mbps)
  net_out_thresh = 1.5
  if net_out_result_mbps <= net_out_thresh:
      print("Network out Warning, NetSpeed at:", net_out_result_mbps, "mbps")
net_in()
net_out()

Ответы [ 2 ]

1 голос
/ 26 мая 2020

Причина, по которой ваши функции возвращают только 0, заключается в том, что, когда вы вычисляете разницу после вашей time.sleep(1) команды, вы не запрашиваете интерфейс для новой статистики. Вы в основном вычисляете 1000-1000.

Я исправил ваш код и изменил вывод на мегабайты вместо мегабит, потому что psutil возвращает байты, а не биты:

def net_usage(inf = "eth0"):   #change the inf variable according to the interface
    net_stat = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
    net_in_1 = net_stat.bytes_recv
    net_out_1 = net_stat.bytes_sent
    time.sleep(1)
    net_stat = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
    net_in_2 = net_stat.bytes_recv
    net_out_2 = net_stat.bytes_sent

    net_in = round((net_in_2 - net_in_1) / 1024 / 1024, 3)
    net_out = round((net_out_2 - net_out_1) / 1024 / 1024, 3)

    print(f"Current net-usage:\nIN: {net_in} MB/s, OUT: {net_out} MB/s")

Вывод:

Current net-usage:
IN: 24.263 MB/s, OUT: 0.421 MB/s
0 голосов
/ 26 мая 2020

Удалось решить эту проблему, добавив очень простой шаг: -

  net_out_ps1 = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
  net_out_1 = net_out_ps1.bytes_sent
  time.sleep(1)
  net_out_ps2 = psutil.net_io_counters(pernic=True, nowrap=True)[inf]
  net_out_2 = net_out_ps2.bytes_sent

Мне пришлось собирать данные один раз перед сном, а затем еще раз после сна. Очень простая основная ошибка c. Однако, если кто-то может помочь в дальнейшей оптимизации кода, я был бы признателен. Еще раз спасибо.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...