Python 服务器监控

Python 服务器监控

      • 一、安装 paramiko 和 psutil
      • 二、实现远程监控
      • 三、问题 CryptographyDeprecationWarning

一、安装 paramiko 和 psutil

pip install paramiko
pip install psutil

二、实现远程监控

  1. 监控入口 run_perf.py
import os
from utils import *


def run_perf(host, port, user, password):
    """
    读取脚本,执行监控
    """"
    base = os.getcwd()
    cmd_file = base + r'/script.txt'
    client = connect_to_server(host, port, user, password)
    with open(cmd_file) as fp:
        cmd = fp.read()
        exec_script(client, cmd)
    close_connection(client)

if __name__ == '__main__':
    run_perf('10.2.2.100', 22, 'root', 'password')
  1. 远程连接 utils.py
import json
import paramiko
import psutil


def connect_to_server(host, port, user, password):
    """
    SSH 连接服务器
    """"
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect(host, port, user, password)
    return client


def exec_script(client, script):
    """
    运行脚本
    """"
    stdin, stdout, stderr = client.exec_command(script)
    for line in stdout.readlnes():
        data = json.loads(line)
        print(data)


def close_connection(client):
    """
    断开服务器
    """"
    client.clsoe()
  1. 监控脚本 script.py
python <<EOF
import json
import psutil as pu


data = ()
mem_info = {}
mem = pu.virtual_memory()
mem_info['total'] = mem.total
mem_info['available'] = mem.available
mem_info['percent'] = mem.percent
mem_info['used'] = mem.used
mem_info['free'] = mem.free
cpu_info = pu.cpu_percent(interval=2, percpu=True)

data['mem_info'] = mem_info
data['cpu_info '] = cpu_info
data = json.dumps(data)
print(data)
EOF

三、问题 CryptographyDeprecationWarning

  1. 原因:
    paramiko 依赖 cryptography,而最新的 cryptography 里有些弃用的 API。
  2. 解放方案
    uninstall 最新版,安装 2.4.2
    pip uninstall cryptography
    pip install cryptography=2.4.2

PS: 参考链接
https://psutil.readthedocs.io/en/latest/

你可能感兴趣的:(Python,Linux,性能测试,稳定性测试)