其他分享
首页 > 其他分享> > CMDB项目要点总结

CMDB项目要点总结

作者:互联网

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

标签:总结,self,def,ssh,error,要点,import,logger,CMDB
来源: https://www.cnblogs.com/lucas-big-data/p/14366068.html