要点:
import importlib import traceback from lib.config.settings import settings ##插件管理类 class PluginsManager(): def __init__(self, hostname=None): self.pluginSettings = settings.PLUGINS_DICT self.mode = settings.MODE self.hostname = hostname self.debug = settings.DEBUG if self.mode == 'ssh': self.ssh_port = settings.SSH_PORT self.ssh_username = settings.SSH_USERNAME self.ssh_pwd = settings.SSH_PWD self.ssh_hostname = settings.SSH_HOSTNAME def execute(self): # 1. 获取配置 # 2. 循环执行 response = {} #获取PLUGINS_DICT这个字典的 key与 values的值 for k,v in self.pluginSettings.items(): ret = {'code': 1000, 'data': None} try: #k:basic v: src.plugins.basic.Basic module_name , class_name = v.rsplit('.',1) #因为得到的是字符串,吧字符串当作模块导入 m = importlib.import_module(module_name) cls = getattr(m,class_name) res = cls().process(self.command, self.debug) ret['data'] =res response[k]=ret except Exception as e: ret['code'] =1001 #注意traceback模块可以直接显示报错的位置和内容,更直观 ret['data'] ="[%s] 模式下的主机 [%s] 采集[%s]出错,出错信息是:[%s]" % (self.mode, self.hostname if self.hostname else 'agent', k, traceback.format_exc()) response[k] = ret return response def command(self,cmd): if self.mode == 'agent': return self.__agent(cmd) elif self.mode == 'ssh': return self.__ssh(cmd) elif self.mode == 'salt': return self.__salt(cmd) else: return '只支持采集模式为:agent/ssh/salt模式' def __agent(self,cmd): import subprocess res = subprocess.getoutput(cmd) return res def __ssh(self,cmd): import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(hostname=self.ssh_hostname,port=self.ssh_port,username=self.ssh_username, password=self.ssh_pwd) stdin, stdount, stderr = ssh.exec_command(cmd) result = stdount.read() ssh.close() return result def __salt(self,cmd): import subprocess res_cmd = "salt '%s' cmd.run '%s'" %(self.hostname,cmd) res = subprocess.getoutput(res_cmd) return res
class Basic(object): def __init__(self): pass #这里执行就是__init__文件内的 res = cls().process(self.command, self.debug) #其实就是运行了 Basci().process方法 def process(self,command_func,debug): if debug: output = { 'os_platform': 'linux', 'os_version': 'CentOS release 6.6 (Final)\nKernel \r on an \m', 'hostname': 'nod1.com' } else: output = { 'os_platform': command_func("uname").strip(), 'os_version': command_func("cat /etc/issue").strip().split('\n')[0], 'hostname': command_func("hostname").strip(), } return output
import os from lib.config.settings import settings class Board(object): def __init__(self): pass @classmethod def initial(cls): return cls() def process(self,command_func,debug): if debug: output = open(os.path.join(settings.BASEDIR, 'files/board.out'), 'r',encoding='utf-8').read() else: output = command_func("sudo dmidecode -t1") return self.parse(output) def parse(self,content): result ={} key_map = { 'Manufacturer': 'manufacturer', 'Product Name': 'model', 'Serial Number': 'sn', } for item in content.split('\n'): #进行切片,成为列表形式 row_data = item.strip().split(':') #过滤,显示想要的,当列表中有2个值说明是我们想要的 if len(row_data) ==2: #如果索引1的key值是在key_map中,进行过滤 if row_data[0] in key_map: result[key_map[row_data[0]]] = row_data[1].strip() if row_data[1] else row_data[1] return result
来源:https://www.cnblogs.com/gukai/p/10872159.html