CMDB项目要点总结之中控机
阅读原文时间:2023年07月12日阅读:1

1.基于paramiko对远程主机执行命令操作

秘钥形式

private_key = paramiko.RSAKey.from_private_key_file('c:/Users/用户名/.ssh/id_rsa')

# 创建ssh对象
ssh = paramiko.SSHClient()
# 运行连接不在know_host文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='主机名', port='端口号', username='用户名', pkey=private_key)
# 执行命令
stdin, stdout, stderr = ssh.exec_command("命令")
# 获取结果
result = stdout.read()

# 关闭连接
ssh.close()

2.线程池提高效率

from concurrent.futures import ThreadPoolExecutor
# 创建一个十个线程的线程池
def task(i):
   print("我是任务%s" % i)
pool = ThreadPoolExecutor(10)
for i in range(10):
   pool.submit(task,i)

3.基于logging模块进行日志的提取

import logging
import traceback
# import settings

class Logger(object):
    def __init__(self, file_path, level):
        file_handler = logging.FileHandler(file_path, 'a', encoding='utf-8')
        fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s: %(message)s")
        file_handler.setFormatter(fmt)

        self.logger = logging.Logger('cmdb', level=level)
        self.logger.addHandler(file_handler)

    def error(self, msg):
        self.logger.error(msg)

logger = Logger("你的日志存放路径", logging.DEBUG)

logger.error(traceback.format_exc())  # 获取异常堆栈信息

4.基于类的封装对数据进行封装

class BaseResponse(object):
    def __init__(self, status=True, data=None, error=None):
        self.status = status
        self.data = data
        self.error = error

    @property  # 作用:让调用着不用加()
    def dict(self):
        return self.__dict__

5.基于工厂模式和反射对资产数据进行获取

def get_server_info(ssh, hostname):
    server_info = {}
    for key, path in settings.PLUGIN_CLASS_DICT.items():
        module_path, class_name = path.rsplit('.', maxsplit=1)
        try:
            module = importlib.import_module(module_path)
        except Exception as e:
            print(e)
        cls = getattr(module, class_name)
        plugin_obj = cls()
        info = plugin_obj.process(ssh, hostname)
        server_info[key] = info
    return server_info


# settings.py
# 获取计算机信息配置
PLUGIN_CLASS_DICT = {
    'basic': 'lib.plugin.basic.BasicPlugin',
    'disk': 'lib.plugin.disk.DiskPlugin',
    'memory': 'lib.plugin.memory.MemoryPlugin',
    'network': 'lib.plugin.network.NetworkPlugin',
}


# disk.py
import traceback
from lib.utils.log import logger
from lib.utils.response import BaseResponse

class DiskPlugin(BasePlugin):
    """
    获取磁盘信息
    """
    def process(self, ssh, hostname):
        result = BaseResponse()
        try:
            # output = ssh(hostname, 'MegaCli -PDList -aALL')
            output = open('files/disk.out').read()
            result.data = output
            output.close()
        except Exception as e:
            logger.error(traceback.format_exc())
            result.status = False
            result.error = traceback.format_exc()
        return result.dict

6.采集资产用到的命令

cpu:
    cat /proc/cpuinfo
主板:
    dmidecode -t1
内存:
    dmidecode -q -t 17 2>/dev/null
网卡(salt源码):
    ip link show
    ip addr show
硬盘:
    MegaCli -PDList -aALL

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器