Python 自动化巡检服务器并分析数据

Python 自动化巡检服务器并分析数据

1、期望目标:

  • 通过 Python 实现 自动化巡检,包含CPU、内存指标、进程指标,并且生成表格
  • 加入配置文件的概念配置,Python脚本会读取配置文件,根据配置文件的配置,去巡检服务器
  • 实际效果:
    • 执行py脚本使用 -configfile 指定配置文件,就可以实现我们想要巡检的机器、认证方式、生成表格的文件名

以下开发坏境为:Python3.9.10

以上就单纯这么做的话就太 low 了,数据都采集出来了,肯定要做数据分析啊,反正都有数据之后再把数据分析加上

2、示例表格

主机名称 IP 地址 CPU 核心 CPU 空闲率 CPU 使用率 内存总大小 内存使用大小

3、安装库依赖(以下的依赖包都是我在开发过程中使用到的,请现在服务器上安装好包)

# 更新pip
python -m pip install --upgrade pip --trusted-host mirrors.aliyun.com
# 先下来以下软件包,如果下载不下来就执行上面的更新命令,再下载
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple wheel
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple paramiko
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple openpyxl
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple requests
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple tqdm
pip3 install -i https://pypi.tuna.tsinghua.edu.cn/simple plotly

pip3 install wheel

  • 安装了wheel包,wheel是Python的一种打包格式,它比传统的.egg格式更高效,可以显著加快包的安装速度。

pip3 install paramiko

  • 安装了paramiko包,这是一个实现了SSHv2协议的Python库,常用于进行远程服务器上的文件传输和命令执行。

pip3 install pandas

  • 安装了pandas包,这是一个强大的数据分析和操作库,提供了高性能的数据结构和数据分析工具。

pip3 install openpyxl

  • 安装了openpyxl包,这是一个用于读写Microsoft Excel 2010 xlsx/xlsm/xltx/xltm文件格式的库。

pip3 install tqdm

  • 显示进度条

pip3 install plotly

  • 它提供了一种交互式的绘图体验,能够创建出既美观又功能丰富的图表

一、编写Py巡检脚本

1、编写 py 脚本

#!/usr/bin/python3
import openpyxl
import paramiko
import pandas as pd
from openpyxl.styles import Alignment
from datetime import datetime
import requests
import configparser
import argparse
import os
from tqdm import tqdm


def connect_server(servers, df):
    for server_info in tqdm(servers,desc="巡检服务器"):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        try:
            if 'key_filename' in server_info:
                ssh.connect(server_info['hostname'], port=server_info['port'], username=server_info['username'],
                            key_filename=server_info['key_filename'])

            elif 'password' in server_info:
                ssh.connect(server_info['hostname'], port=server_info['port'], username=server_info['username'],
                            password=server_info['password'])

            _, stdout, _ = ssh.exec_command('hostname')
            hostname = stdout.read().decode('utf-8').strip()

            _, stdout, _ = ssh.exec_command('cat /proc/cpuinfo | grep processor | wc -l')
            cpu_process = stdout.read().decode('utf-8').strip()

            _, stdout, _ = ssh.exec_command(r'top -bn1 | grep "Cpu(s)" | sed "s/.*, *\([0-9.]*\)%* id.*/\1/"')
            cpu_free = stdout.read().decode('utf-8').strip()


            _, stdout, _ = ssh.exec_command('top -bn1 | grep "Cpu(s)" | awk \'{print $2}\'')
            user_cpu_usage = stdout.read().decode('utf-8').strip()


            _, stdout, _ = ssh.exec_command('top -bn1 | grep "Cpu(s)" | awk \'{print $4}\'')
            system_cpu_usage = stdout.read().decode('utf-8').strip()


            _, stdout, _ = ssh.exec_command('free -g | grep "Mem" | awk \'{print $2}\'')
            total_memory_gb = stdout.read().decode('utf-8').strip()


            _, stdout, _ = ssh.exec_command('free -m | grep "Mem" | awk \'{print $2}\'')
            total_memory_mb = stdout.read().decode('utf-8').strip()


            _, stdout, _ = ssh.exec_command('free -g | grep "Mem" | awk \'{print $NF}\'')
            application_free_gb = stdout.read().decode('utf-8').strip()

            _, stdout, _ = ssh.exec_command('free -m | grep "Mem" | awk \'{print $NF}\'')
            application_free_mb = stdout.read().decode('utf-8').strip()


            _, stdout, _ = ssh.exec_command('ps -A -o pid= | wc -l')
            total_process = stdout.read().decode('utf-8').strip()

            _, stdout, _ = ssh.exec_command('ps -eo state | grep -c \'^R\'')
            running_process = stdout.read().decode('utf-8').strip()

            _, stdout, _ = ssh.exec_command('ps -eo state | grep -c \'^S\'')
            sleep_process = stdout.read().decode('utf-8').strip()

            _, stdout, _ = ssh.exec_command('ps -eo state | grep -c \'^T\'')
            stop_process = stdout.read().decode('utf-8').strip()

            _, stdout, _ = ssh.exec_command('ps -eo state | grep -c \'^T\'')
            zombie_process = stdout.read().decode('utf-8').strip()

            def get_public_ip():
                response = requests.get('https://api.ipify.org')
                if response.status_code == 200:
                    return response.text
                else:
                    return None

            df = df.append({
   
                'Date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'Hostname': hostname,
                'Local IP/EIP': f"{
     server_info['hostname']}/{
     get_public_ip()}",
                'CPU Process': cpu_process,
                'CPU Free (%)': cpu_free,
                'User CPU Usage (%)': user_cpu_usage,
                'System CPU Usage (%)': system_cpu_usage,
                'Process Total/Running/Sleep/Stop/Zombie': f"{
     total_process}/{
     running_process}/{
     sleep_process}/{
     stop_process}/{
     zombie_process}",
                'Total Memory Size (GB/MB)': f"{
     total_memory_gb}/{
     total_memory_mb}",
                'Application Free Size (GB/MB)'
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值