CMDB-客户端
配置文件的设置
大体思路:
1,通过开始文件将用户配置信息的文件放置到环境变量中。
2,在lib文件中的config文件中,从环境变量中获取到用户的配置,通过importlib模块导入用户配置文件,通过dir方法获取到文件內的配置信息加载到本Settings类中。
3,默认配置方式同上。
import os os.environ["USER_SETTINGS"] = "config.settings" from lib.conf.config import settings print(settings.USER) print(settings.EMAIL)
""" 用户自定义配置 """ USER = "root" EMAIL = "chenrun@163.com"
默认配置信息
""" 全局配置文件 """ import os import importlib from . import global_settings class Settings(object): def __init__(self): # 找到默认配置 for name in dir(global_settings): value = getattr(global_settings, name) setattr(self, name, value) # 找到自定义配置 settings_module = os.environ.get("USER_SETTINGS") # 根据字符串导入模块 if settings_module: m = importlib.import_module(settings_module) for name in dir(m): if name.isupper(): value = getattr(m, name) setattr(self, name, value) settings = Settings()
执行流程的大体思路:
basic.py
class Basic(object): def process(self): return "123123123"
init.py文件
从配置文件中获取到所有需要采集的硬件信息,通过importlib导入,并执行每个类里的process方法。
import importlib from lib.conf.config import settings class PluginManager(object): def __init__(self, hostname=None): self.hostname = hostname self.plugin_dict = settings.PLUGINS_DICT def exec_plugin(self): """ 获取所有的插件,并执行获取插件的返回值 :return: """ response = {} for k, v in self.plugin_dict.items(): # 'basic': "src.plugins.basic.Basic" prefix, class_module = v.rsplit(".", 1) m = importlib.import_module(prefix) cls = getattr(m, class_module) result = cls().process() response[k] = result return response
start.py文件
通过sys.path.append() 导入根目录,方便导入src中的模块
import os os.environ["USER_SETTINGS"] = "config.settings" import sys BASEDIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(BASEDIR) from src.plugins import PluginManager if __name__ == '__main__': server_info = PluginManager().exec_plugin() print(server_info)
后续在init中执行分别定义不同的连接方式,agent,paramiko,saltstack。
src下创建client与script文件
client处理发送API,获取资产信息,获取ssh
import json import requests from src.plugins import PluginManager from lib.conf.config import settings class Base(object): def post_asset(self, server_info): requests.post(settings.API, json=server_info) class Agent(Base): def execute(self): server_info = PluginManager().exec_plugin() self.post_asset(server_info) class SSHSALT(Base): def get_host(self): # 获取未采集的主机列表 response = requests.get(settings.API) result = json.loads(response.text) if not result["status"]: return return result["data"] def execute(self): host_list = self.get_host() for host in host_list: server_info = PluginManager(host).exec_plugin() self.post_asset(server_info)
script.py文件对不同的模式进行判断返回obj对象
from . import client from lib.conf.config import settings def run(): if settings.MODE == "AGENT": obj = client.Agent() else: obj = client.SSHSALT() obj.execute()