CMDB02/ 单例模式、资产采集参考命令、日志处理
CMDB02/单例模式、资产采集参考命令、日志处理
1. 单例模式
1.1 多例模式
代码示例
class Foo(object):
def __init__(self,name,age):
self.name = name
self.age = age def func(self):
msg = "%s-%s" %(self.name,self.age) obj1 = Foo("张三",18) # Foo的一个对象/Foo类的一个实例
obj1.func() obj2 = Foo("李四",19)
obj2.func()
1.2 单例模式
代码示例/以前:
class Foo(object):
instance = None
def __init__(self,name,age):
self.name = name
self.age = age def __new__(cls,*arg,**kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
class Singleton(object):
instance = None def __init__(self):
self.name = None def __new__(cls, *arg, **kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
应用场景:
django配置文件,只要加载一次,以后使用都用同一份值。
class Singleton(object):
instance = None def __init__(self):
self.k0 = 0
self.k1 = 1
self.k2 = 2
... def __new__(cls, *arg, **kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance obj1 = Singleton()
obj2 = Singleton()
obj3 = Singleton()
django的admin,在注册models中用,希望所有的model类注册到同一个列表中。
1.2.1 单例模式/错误
代码示例:
class Singleton(object):
instance = None def __init__(self):
self.name = None def __new__(cls, *arg, **kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
1.2.2 单例模式 new/正确
代码示例:
import time
import threading class Singleton(object):
instance = None
lock = threading.RLock() def __new__(cls, *arg, **kwargs):
if cls.instance:
return cls.instance
with cls.lock:
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance obj1 = Singleton()
obj2 = Singleton()
1.2.3 单例模式之文件导入/正确,在源码中的应用
代码示例1:
# xx.py class Site(object):
def __init__(self):
self.names = [] def xx(self):
pass
site = Site()
import xx print(xx.site)
代码示例2:
# xx.py class Singleton(object): def __init__(self):
self._registry = [] def register(self,model_class):
self._registry.append(model_class) site = Singleton()
import xx
xx.site
1.3 单例模式补充
基于
__new__实现单例模式,在init中不设置值。是单例,但数据会被覆盖
class Singleton(object):
instance = None def __init__(self):
self.registry = [] def __new__(cls, *arg, **kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance def register(self, val):
self.registry.append(val) # {registry:[]}
obj1 = Singleton()
# {registry:[x1]}
obj1.register('x1') # instance = {registry:[x1]}
# instance = {registry:[]}
obj2 = Singleton()
# instance = {registry:[x2]}
obj2.register('x2') print(obj2.registry)
print(obj1.registry)
单例模式/数据不会覆盖
class Singleton(object):
instance = None
registry = [] def __new__(cls, *arg, **kawrgs):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance def register(self, val):
self.registry.append(val) obj1 = Singleton()
obj1.register('x1') obj2 = Singleton()
obj2.register('x2') print(obj2.registry)
print(obj1.registry)
2. 日志
代码示例:
import logging
import settings class AutoLogger(object):
def __init__(self,log_path,log_name):
file_handler = logging.FileHandler(log_path, 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s")
file_handler.setFormatter(fmt) self.logger = logging.Logger(log_name, level=logging.DEBUG)
self.logger.addHandler(file_handler) def log(self,msg):
self.logger.error(msg) logger = AutoLogger(settings.LOG_FILE_PATH,'cmdb')
获取日志堆栈信息
import traceback def run():
try:
int('lbzhk')
except Exception as e:
print(traceback.format_exc()) if __name__ == '__main__':
run()
3. 获取资产信息的命令
内存信息
sudo dmidecode -q -t 17 2>/dev/null # 注意:linux上要提前安装 yum install dmidecode
硬盘(安装MegaCli)
sudo MegaCli -PDList -aALL
网卡
sudo ip link show
sudo ip addr show
主板
sudo dmidecode -t1
CPU
cat /proc/cpuinfo
4. 数据封装
代码示例:
class BaseResponse(object):
def __init__(self):
self.status = True
self.data = None
self.error = None
@property
def dict(self):
return self.__dict__ def process():
info = BaseResponse()
try:
info.status = True
info.data = "lbzhk"
except Exception:
pass
return info.dict result = process()
print(result)
5.表关系

总结:
cmdb资产采集后,为什么不直接放到数据库?
- 单独编写api,为了给其他系统提供数据支持(接口)
- 维护的数据库连接比较多,修改不方便。
手写单例模式
- new+锁
其他单例模式
使用模块
class Singleton(object):
def foo(self):
pass
singleton = Singleton()
from a import singleton
使用装饰器
def Singleton(cls):
_instance = {} def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls] return _singleton @Singleton
class A(object):
a = 1
def __init__(self, m=0):
self.m = m a1 = A(1)
a2 = A(2)
使用类 -- 可以防止多线程的时候出问题
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock() def __init__(self):
time.sleep(1) @classmethod
def instance(cls, *args, **kwargs):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
time.sleep(20)
obj = Singleton.instance()
print(obj)
基于
__new__实现 ,代码如上
__new__方法返回的是什么- 新创建的对象,内部没有数据,需要经过init来进行初始化。
单利模式应用场景:
- django的配置文件
- django的admin
- 数据库链接池(单例模式)
- 写日志
CMDB02/ 单例模式、资产采集参考命令、日志处理的更多相关文章
- Django项目:CMDB(服务器硬件资产自动采集系统)--12--08CMDB采集硬件数据日志记录
#settings.py # ————————01CMDB获取服务器基本信息———————— import os BASEDIR = os.path.dirname(os.path.dirname(o ...
- CMDB资产采集方案
CMDB资产采集方案 CMDB 资产采集的方案总共有四种 Agent SSH类 Saltstack Puttet 方案设计,从性能上考虑 下面前三种是用Python开发的,目标是兼容三种采集方式的软件 ...
- CMDB学习之八,完成所有资产采集信息的收集
#!/usr/bin/env python # -*- coding:utf-8 -*- import traceback from .base import BasePlugin from lib. ...
- CMDB03 /今日未采集的资产、资产入库、资产变更记录、资产采集
CMDB03 /今日未采集的资产.资产入库.资产变更记录.资产采集 目录 CMDB03 /今日未采集的资产.资产入库.资产变更记录.资产采集 1. 获取今日未采集的服务器 2. server资产入库以 ...
- 应用Flume+HBase采集和存储日志数据
1. 在本方案中,我们要将数据存储到HBase中,所以使用flume中提供的hbase sink,同时,为了清洗转换日志数据,我们实现自己的AsyncHbaseEventSerializer. pac ...
- CMDB资产采集笔记
一.资产采集四种方式 1. Agent方式 API:Django接收数据并入库 程序:放置在每台服务器 应用场景:针对服务器较多的公司 步骤一: #执行本地命令的库 import subprocess ...
- CMDB资产采集的四种方式
转 https://www.cnblogs.com/guotianbao/p/7703921.html 资产采集的概念 资产采集的四种方式:Agent.SSH.saltstack.puppet 资产采 ...
- [日志分析]Graylog2采集mysql慢日志
之前聊了一下graylog如何采集nginx日志,为此我介绍了两种采集方法(主动和被动),让大家对graylog日志采集有了一个大致的了解. 从日志收集这个角度,graylog提供了多样性和灵活性,大 ...
- CMDB服务器管理系统【s5day91】:资产采集相关问题
资产采集唯一标识和允许临时修改主机名 class AgentClient(BaseClient): def exec(self): obj = PluginManager() server_dict ...
随机推荐
- 从0到70%:Chrome上位揭秘!
最近的数据显示,Chrome在2020年4月的市场份额达到了70%左右,把微软的Edge和Firefox远远甩在身后,毫无疑问,Chrome赢得了第二次游览器之战,成为新一代王者. Chrome的第一 ...
- (一)Log4j使用
原文链接:https://www.jianshu.com/p/eb4ac2571c94?tdsourcetag=s_pctim_aiomsg 1.先创建个maven项目,在我们项目的pom文件中导入l ...
- Anroid组件滚动视图(ScollView)简单使用
ScollView应用展示 在xml文件中添加滚动视图 activity_main.xml <?xml version="1.0" encoding="utf-8& ...
- unittest模块在linux报错: AttributeError: module 'unittest' has no attribute 'TestRunner'
一开始在windows下运行没有问题,但是在linux下运行却报如下错误: AttributeError: module 'unittest' has no attribute 'TestRunn ...
- 后渗透工具Empire使用教程
一.前言 Empire是一个PowerShell后期漏洞利用代理工具同时也是一款很强大的后渗透测神器,它建立在密码学.安全通信和灵活的架构之上.Empire实现了无需powershell.exe就可运 ...
- yum 安装JDK
系统:CentOS 7 查看当前系统是否已安装JDK yum list installed |grep java 如果没有就选择yum库中的包进行安装,查看yum库中JDK列表 yum -y list ...
- vue多个项目公共化组件方案
前言 最近项目需求,需要把两个vue项目多个一样的模块抽成公共化.考虑采用的方案 1.把公共部分独立出来一个项目,npm发布私有包,使用的项目npm install下载(目前下载使用出现配置错误) 存 ...
- 【转载】npx 真香
npx 主要提供了一些便捷操作: 调用项目安装的模块 避免全局安装模块 使用不同版本的 node 执行 GitHub 源码 原文地址:http://www.ruanyifeng.com/blog/20 ...
- Python实用笔记 (7)高级特性——切片
列表L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack'] 取前3个元素 >>> L[0:3] ['Michael', 'Sarah', ' ...
- Navicat15安装激活版教程
navicat15安装 一键式安装,安装包如下 链接:https://pan.baidu.com/s/1VTJmJ7ulUySWoWBu-fugiw 提取码:fz5u 先安装软件包点击安装,一直下一步 ...