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 loggingimport traceback# import settingsclass 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] = inforeturn 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.pyimport tracebackfrom lib.utils.log import loggerfrom lib.utils.response import BaseResponseclass DiskPlugin(BasePlugin):"""获取磁盘信息"""def process(self, ssh, hostname):result = BaseResponse()try:# output = ssh(hostname, 'MegaCli -PDList -aALL')output = open('files/disk.out').read()result.data = outputoutput.close()except Exception as e:logger.error(traceback.format_exc())result.status = Falseresult.error = traceback.format_exc()return result.dict
赞 (0)