Django【设计】可插拔的插件方式实现
# 根据字符串形式导入模块,并且找到其中的类并执行
import importlib v = "src.plugins.nic.Nic"
module_path,cls_name = v.rsplit('.',maxsplit=1)
m = importlib.import_module(module_path)
cls = getattr(m,cls_name)
obj = cls()
obj.process()
def exec_plugin(self):
server_info = {}
for k,v in self.plugin_items.items():
# 找到v字符串:src.plugins.nic.Nic,
# src.plugins.disk.Disk
info = {'status':True,'data': None,'msg':None}
try:
module_path,cls_name = v.rsplit('.',maxsplit=1)
module = importlib.import_module(module_path)
cls = getattr(module,cls_name) if hasattr(cls,'initial'):
obj = cls.initial()
else:
obj = cls()
ret = obj.process(self.exec_cmd,self.test)
info['data'] = ret
except Exception as e:
info['status'] = False
info['msg'] = traceback.format_exc() server_info[k] = info
return server_info
import sys
import os BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASEDIR) # 设置全局变量(手动配置路径)
os.environ['AUTO_CLIENT_SETTINGS'] = "conf.settings" # # 导入插件管理类
# from src.plugins import PluginManager from src import script if __name__ == '__main__':
script.start()
from lib.config import settings
from .client import AgentClient
from .client import SaltSshClient def start():
# 这个函数用来判断模式,并约束可选模式
if settings.MODE == 'AGENT':
obj = AgentClient()
elif settings.MODE == "SSH" or settings.MODE == 'SALT':
obj = SaltSshClient()
else:
raise Exception('模式仅支持:AGENT/SSH/SALT')
obj.exec()
import requests,json,time,hashlib
from src.plugins import PluginManager
from lib.config import settings
from concurrent.futures import ThreadPoolExecutor class BaseClient(object):
def __init__(self):
self.api = settings.API def post_server_info(self,server_dict): # requests.post(self.api,data=server_dict) # 1. k=v&k=v, 2. content-type: application/x-www-form-urlencoded
response = requests.post(self.api,json=server_dict,headers={'auth-api':auth_header_val}) # 1. 字典序列化;2. 带请求头 content-type: application/json def exec(self):
raise NotImplementedError('必须实现exec方法') class AgentClient(BaseClient): # 继承BaseClient类 def exec(self):
obj = PluginManager()
server_dict = obj.exec_plugin()
print('采集到的服务器信息:',server_dict)
self.post_server_info(server_dict) class SaltSshClient(BaseClient): # 继承BaseClient类
def task(self,host):
obj = PluginManager(host)
server_dict = obj.exec_plugin()
self.post_server_info(server_dict) def get_host_list(self):
response = requests.get(self.api,headers={'auth-api':auth_header_val})
print(response.text) # [{"hostname":"c1.com"}]
return json.loads(response.text)
# return ['c1.com',] def exec(self):
pool = ThreadPoolExecutor(10) host_list = self.get_host_list()
for host in host_list:
# 注意格式,如果host_list为字典,用host.hostname取值
pool.submit(self.task,host)
import importlib
import requests
from lib.config import settings
import traceback class PluginManager(object):
def __init__(self,hostname=None):
self.hostname = hostname
self.plugin_items = settings.PLUGIN_ITEMS
self.mode = settings.MODE
self.test = settings.TEST
if self.mode == "SSH":
self.ssh_user = settings.SSH_USER
self.ssh_port = settings.SSH_PORT
self.ssh_pwd = settings.SSH_PWD def exec_plugin(self):
server_info = {}
for k,v in self.plugin_items.items():
# 找到v字符串:src.plugins.nic.Nic,
# src.plugins.disk.Disk
info = {'status':True,'data': None,'msg':None}
try:
module_path,cls_name = v.rsplit('.',maxsplit=1)
module = importlib.import_module(module_path)
cls = getattr(module,cls_name) if hasattr(cls,'initial'):
obj = cls.initial()
else:
obj = cls()
ret = obj.process(self.exec_cmd,self.test)
info['data'] = ret
except Exception as e:
info['status'] = False
info['msg'] = traceback.format_exc() server_info[k] = info
return server_info def exec_cmd(self,cmd):
# 调用插件方法时,会把执行命令的方法作为参数传到插件,line:48
if self.mode == "AGENT":
import subprocess
result = subprocess.getoutput(cmd)
elif self.mode == "SSH":
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=self.hostname, port=self.ssh_port, username=self.ssh_user, password=self.ssh_pwd)
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()
ssh.close()
elif self.mode == "SALT":
import subprocess
result = subprocess.getoutput('salt "%s" cmd.run "%s"' %(self.hostname,cmd))
else:
raise Exception("模式选择错误:AGENT,SSH,SALT")
return result
PLUGIN_ITEMS = {
"nic": "api.plugins.nic.Nic",
"disk": "api.plugins.disk.Disk",
"memory": "api.plugins.memory.Memory",
}
manager = PluginManager()
response = manager.exec(server_dict) return HttpResponse(json.dumps(response))
for k,v in self.plugin_items.items():
print(k,v)
# try:
module_path,cls_name = v.rsplit('.',maxsplit=1)
md = importlib.import_module(module_path)
cls = getattr(md,cls_name)
obj = cls(server_obj,server_dict[k])
obj.process()
print(k,v)
Django【设计】可插拔的插件方式实现的更多相关文章
- 在.NET Core中三种实现“可插拔”AOP编程方式(附源码)
一看标题肯定会联想到使用动态编织的方式实现AOP编程,不过这不是作者本文讨论的重点. 本文讨论另外三种在netcore中可实现的方式,Filter(过滤器,严格意义上它算是AOP方式),Dynamic ...
- Django中间件-跨站请求伪造-django请求生命周期-Auth模块-seettings实现可插拔配置(设计思想)
Django中间件 一.什么是中间件 django中间件就是类似于django的保安;请求来的时候需要先经过中间件,才能到达django后端(url,views,models,templates), ...
- 在可插拔settings的基础上加入类似中间件的设计
在可插拔settings的基础上加入类似中间件的设计 settings可插拔设计可以看之前的文章 https://www.cnblogs.com/zx125/p/11735505.html 设计思路 ...
- Django数据库设计中字段为空的方式
今天在做数据库设计的时候,设计了如下User表,其中我把email和phone字段设置为允许为空: class User(models.Model): username = models.CharFi ...
- ARM上的linux如何实现无线网卡的冷插拔和热插拔
ARM上的linux如何实现无线网卡的冷插拔和热插拔 fulinux 凌云实验室 1. 冷插拔 如果在系统上电之前就将RT2070/RT3070芯片的无线网卡(以下简称wlan)插上,即冷插拔.我们通 ...
- WPF 插拔触摸设备触摸失效
原文:WPF 插拔触摸设备触摸失效 最近使用 WPF 程序,在不停插拔触摸设备会让 WPF 程序触摸失效.通过分析 WPF 源代码可以找到 WPF 触摸失效的原因. 在 Windows 会将所有的 H ...
- SphereEx 登陆 ApacheCon Asia|依托 ShardingSphere 可插拔架构体系打造数据应用完整生态
2021 年 8 月 8 日,ApacheCon 首次亚洲大会于线上正式闭幕.作为久负盛名的开源盛宴,本届 ApacheCon Asia 受到了海内外众多开源领域人士的关注. 作为 Apache 软件 ...
- 我心中的核心组件(可插拔的AOP)~第二回 缓存拦截器
回到目录 AOP面向切面的编程,也称面向方面的编程,我更青睐于前面的叫法,将一个大系统切成多个独立的部分,而这个独立的部分又可以方便的插拔在其它领域的系统之中,这种编程的方式我们叫它面向切面,而这些独 ...
- 带卡扣的网卡接口使用小Tips,大家注意插拔网线的手法啊!
最近入手了一台X401,因为机器本身比较薄,它的网卡接口是有卡扣的,插网线的时候卡扣往下沉,这种设计应该有很多机型都采用了.但是大家有没有发现啊,这种接口的卡扣,时间长了,可能会有点松动.为了保护爱机 ...
随机推荐
- 【转】自编码算法与稀疏性(AutoEncoder and Sparsity)
目前为止,我们已经讨论了神经网络在有监督学习中的应用.在有监督学习中,训练样本时有类别标签的.现在假设我们只有一个没带类别标签的训练样本集合 ,其中 .自编码神经网络是一种无监督学习算法,它使用了 ...
- BZOJ4573:[ZJOI2016]大森林——题解
http://www.lydsy.com/JudgeOnline/problem.php?id=4573 https://www.luogu.org/problemnew/show/P3348#sub ...
- BZOJ2226 & SPOJ5971:LCMSum——题解
http://www.lydsy.com/JudgeOnline/problem.php?id=2226 题目大意:给定一个n,求lcm(1,n)+lcm(2,n)+……+lcm(n,n). ———— ...
- UOJ228:基础数据结构练习题——题解
http://uoj.ac/problem/228 参考:https://www.cnblogs.com/ljh2000-jump/p/6357583.html 考虑当整个区间的最大值开方==最小值开 ...
- URAL.1033 Labyrinth (DFS)
URAL.1033 Labyrinth (DFS) 题意分析 WA了好几发,其实是个简单地DFS.意外发现这个俄国OJ,然后发现ACRUSH把这个OJ刷穿了. 代码总览 #include <io ...
- HDU 2700
Parity Time Limit: 2000/1000 MS(Java/Others) Memory Limit: 32768/32768 K (Java/Others) Total Subm ...
- 【枚举暴力】【UVA11464】 Even Parity
传送门 Description 给你一个0/1矩阵,可以将矩阵中的0变成1,问最少经过多少此操作使得矩阵任意一元素四周的元素和为偶数. Input 第一行是一个整数T代表数据组数,每组数据包含以下内容 ...
- vue中使用 contenteditable 制作输入框并使用v-model做双向绑定
<template> <div class="div-input" :class="value.length > 0 ? 'placeholder ...
- 爬虫实例——爬取煎蛋网OOXX频道(反反爬虫——伪装成浏览器)
煎蛋网在反爬虫方面做了不少工作,无法通过正常的方式爬取,比如用下面这段代码爬取无法得到我们想要的源代码. import requests url = 'http://jandan.net/ooxx' ...
- Unity3D开发七惑
使用Unity3D开发也有大半年了,心中存惑如下,愿与各位开发者一起探讨: (1) 远离普适编程之惑 随着游戏引擎的不断发展,游戏程序员的开发层级也越来越高,以unity3d尤为突出.如果是进行We ...