python+deepseek自动巡检华为设备

import paramiko
import json
import logging
from datetime import datetime
import os
import traceback
 
# 配置日志记录
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("huawei_inspection.log"),
        logging.StreamHandler()
    ]
)
 
# 设备登录信息(建议使用环境变量或配置文件存储敏感信息)
devices = [
    {
        "host": "192.168.1.1",
        "username": "admin",
        "password": "Admin@123",
        "port": 22,
        "device_type": "Huawei"
    }
]
 
# 采集命令列表(可根据需要扩展)
commands = [
    "display cpu-usage",            # CPU利用率
    "display memory-usage",         # 内存利用率
    "display interface",            # 接口状态与错误计数
    "display current-configuration | include sysname"# 设备名称
    "display version",              # 版本信息
    "display health",               # 设备健康状态
]
 
def collect_data(host, username, password, port, device_type="Huawei"):
    """
    通过SSH收集设备运行状态数据
     
    :param host: 设备IP地址
    :param username: 登录用户名
    :param password: 登录密码
    :param port: SSH端口
    :param device_type: 设备类型
    :return: 收集的设备数据字典
    """
    ssh = paramiko.SSHClient()
    try:
        # 自动添加未知主机的密钥
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
         
        # 设置连接超时和命令执行超时
        ssh.connect(
            host,
            port=port,
            username=username,
            password=password,
            timeout=10# 连接超时
            auth_timeout=10  # 认证超时
        )
         
        # 准备数据字典
        data = {
            "host": host,
            "device_type": device_type,
            "timestamp": str(datetime.now()),
            "commands_output": {}
        }
         
        # 执行每个命令并记录输出
        for cmd in commands:
            try:
                stdin, stdout, stderr = ssh.exec_command(cmd, timeout=15# 命令执行超时
                output = stdout.read().decode('utf-8', errors='ignore').strip()
                error = stderr.read().decode('utf-8', errors='ignore').strip()
                 
                data["commands_output"][cmd] = {
                    "output": output,
                    "error": error
                }
                 
                # 记录命令执行情况
                if error:
                    logging.warning(f"Command '{cmd}' on {host} produced error: {error}")
            except Exception as cmd_error:
                logging.error(f"Error executing command '{cmd}' on {host}: {cmd_error}")
                data["commands_output"][cmd] = {
                    "output": "",
                    "error": str(cmd_error)
                }
         
        return data
     
    except paramiko.AuthenticationException:
        logging.error(f"Authentication failed for {host}")
        return None
    except paramiko.SSHException as ssh_error:
        logging.error(f"SSH connection to {host} failed: {ssh_error}")
        return None
    except Exception as e:
        logging.error(f"Unexpected error connecting to {host}: {e}")
        logging.error(traceback.format_exc())
        return None
    finally:
        # 确保SSH连接被关闭
        try:
            ssh.close()
        except:
            pass
 
def main():
    """
    主执行函数:收集设备数据并保存
    """
    # 创建输出目录(如果不存在)
    os.makedirs("inspection_data", exist_ok=True)
     
    # 存储采集结果
    results = []
     
    # 遍历设备列表
    for device in devices:
        logging.info(f"开始采集设备: {device['host']}")
        device_data = collect_data(**device)
         
        if device_data:
            results.append(device_data)
            logging.info(f"成功采集设备 {device['host']} 的数据")
        else:
            logging.error(f"无法采集设备 {device['host']} 的数据")
     
    # 生成带有时间戳的文件名
    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
    output_file = f"inspection_data/huawei_inspection_{timestamp}.json"
     
    # 保存数据
    try:
        with open(output_file, "w", encoding='utf-8') as f:
            json.dump(results, f, ensure_ascii=False, indent=2)
        logging.info(f"数据已保存到 {output_file}")
    except Exception as e:
        logging.error(f"保存数据时发生错误: {e}")
 
if __name__ == "__main__":
    main()
posted @ 2025-04-10 14:31  小馒头TT  阅读(183)  评论(0)    收藏  举报