def __init__(self, socket, config, framework): BasePlugin.__init__(self, socket, config, framework) self.rfile = SocketIO(socket, "r") self.wfile = SocketIO(socket, "w") socket.settimeout(60)
def setup(self, cfg): BasePlugin.setup(self, cfg) self.factory = MpdFactory(plugin=self) self.factory.plugin = self self.client = TCPClient(self.cfg.get("host", "localhost"), self.cfg.get("port", 6600), self.factory)
def test_get_entry(self): # Try a PUT test_client, test_server = setup_test_sockets(8083) plugin_test = BasePlugin(test_server, setup_test_config(8083, 'http', 'HTTPPlugin'), None) self.assertEqual(plugin_test.get_entry(), {'test': {'command': '', 'path': '', 'headers': '', 'body': ''}}) test_server.close() test_client.close()
def setup(self, cfg): BasePlugin.setup(self, cfg) self.pn = Pubnub(cfg.get("publish_key"), cfg.get("subscribe_key"), cfg.get("secret_key"), cfg.get("ssl_enabled", False)) self.pn.subscribe({ "channel": cfg.get("channel", "default"), "connect": self.on_connect, "callback": self.on_message }) self.subscribe(self.on_event)
def exec_cmd(cmd, ip, kwargs): value_dic = {} contents = BasePlugin(**kwargs).exec_shell_cmd(cmd) if contents['ERROR'] == "": status = 0 else: status = 1 if status != 0: value_dic["ip_addr"] = ip value_dic["enabled"] = 0 #主机不可用 value_dic["hostname"] = "NULL" value_dic["comment"] = contents['ERROR'] else: li = contents['RESULT'].split() # 字符串转列表 print(li) if li[0] in settings.os_type_choices: #判断操作系统是否在列表中 os_type = settings.os_type_choices.get(li[0]) else: os_type = 3 value_dic["ip_addr"] = ip value_dic["enabled"] = 1 #主机可用 value_dic["os_type"] = os_type value_dic["hostname"] = li[1] value_dic["comment"] = "" hostinfo_li.append(value_dic) # if __name__ == '__main__': # kwargs={'192.168.2.112': ['root', 'oracle', 23, 'scott', 'tiger', 'prod', 1521,1]} # # kwargs={'10.10.0.2': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521],'192.168.2.128': ['root', 'qqq', 22, 'scott', 'tiger', 'prod', 1521]} # # kwargs={'192.168.2.128': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521],'192.168.2.129': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521],'10.10.0.2': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521]} # a=monitor(**kwargs) # print(a)
def monitor(frist_invoke=1,**kwargs): for i,v in kwargs.items(): ip = i #print(ip,username,port,passwd) shell_command = 'sar 1 3| grep "^Average:"' contents = BasePlugin(**kwargs).exec_shell_cmd(shell_command) if contents['ERROR'] == "" : contents['ERROR'] = 0 else: contents['ERROR'] = 1 status = contents['ERROR'] if status != 0: value_dic = {'ip': ip,'status': status} else: value_dic = {} run_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') #print('---res:',contents['RESULT']) user,nice,system,iowait,steal,idle = contents['RESULT'].split()[2:] value_dic= { 'ip': ip, 'user': user, 'nice': nice, 'system': system, 'idle': idle, 'time': run_time, 'status': status } return value_dic
def monitor(frist_invoke=1, **kwargs): for i, v in kwargs.items(): ip = i shell_command = 'sar -n DEV 1 5 |grep -v IFACE |grep Average' contents = BasePlugin(**kwargs).exec_shell_cmd(shell_command) #result = subprocess.Popen(shell_command,shell=True,stdout=subprocess.PIPE).stdout.readlines() #print(result) if contents['ERROR'] == "": contents['ERROR'] = 0 else: contents['ERROR'] = 1 status = contents['ERROR'] value_dic = {'status': 0, 'data': {}} li = contents['RESULT'].split("\n") # 字符串转列表 content_list = li[:len(li) - 1] # 取列表开始到倒数第二个元素,最后一个元素为空 if status != 0: value_dic = {'status': status} else: value_dic = {'status': 0, 'data': {}} li = contents['RESULT'].split("\n") # 字符串转列表 content_list = li[:len(li) - 1] # 取列表开始到倒数第二个元素,最后一个元素为空 for line in content_list: line = line.split() nic_name, t_in, t_out = line[1], line[4], line[5] value_dic['data'][nic_name] = {"t_in": line[4], "t_out": line[5]} return value_dic
def monitor(frist_invoke=1,**kwargs): for i,v in kwargs.items(): ip = i username = v[0] passwd = v[1] port = v[2] value_dic = {} shell_command = 'uptime' contents = BasePlugin(ip,port,username,passwd).exec_shell_cmd(shell_command) run_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') # contents = BasePlugin('192.168.2.128', 22, 'root', 'oracle').exec_shell_cmd(shell_command) if contents['ERROR'] == "" : contents['ERROR'] = 0 else: contents['ERROR'] = 1 status = contents['ERROR'] if status != 0: value_dic = {'status': status} #user,nice,system,iowait,steal,idle = result.split()[2:] else: value_dic= { 'ip':ip, 'uptime': contents['RESULT'], 'time':run_time, 'status': 0 } return value_dic # if __name__ == '__main__': # host_message = {'192.168.2.128': ['root', 'oracle', 22]} # a = monitor(**host_message) # print(a)
def setup(self, cfg): BasePlugin.setup(self, cfg) self.factory = MZMQFactory(plugin=self) self.factory.plugin = self self.pub_endpoint_uri = cfg.get("pub_endpoint", "tcp://*:9901") self.pub_endpoint = ZmqEndpoint("bind", self.pub_endpoint_uri) self.sub_endpoint_uri = cfg.get("sub_endpoint", "tcp://*:9901") self.sub_endpoint = ZmqEndpoint("connect", self.sub_endpoint_uri) self.pub = ZmqPubConnection(self.factory, self.pub_endpoint) self.sub = ZmqSubConnection(self.factory, self.sub_endpoint) self.sub.subscribe("") self.sub.gotMessage = self.on_message self.subscribe(self.process_event)
def setup(self, cfg): BasePlugin.setup(self, cfg) self.pn = Pubnub( cfg.get("publish_key"), cfg.get("subscribe_key"), cfg.get("secret_key"), cfg.get("ssl_enabled", False) ) self.pn.subscribe({ "channel": cfg.get("channel", "default"), "connect": self.on_connect, "callback": self.on_message }) self.subscribe(self.on_event)
def monitor(frist_invoke=1, **kwargs): for i, v in kwargs.items(): ip = i monitor_dic = { 'SwapUsage': 'percentage', 'MemUsage': 'percentage', } shell_command = "grep 'MemTotal\|MemFree\|Buffers\|^Cached\|SwapTotal\|SwapFree' /proc/meminfo" contents = BasePlugin(**kwargs).exec_shell_cmd(shell_command) run_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') if contents['ERROR'] == "": contents['ERROR'] = 0 else: contents['ERROR'] = 1 status = contents['ERROR'] if status != 0: #cmd exec error value_dic = {'status': status} else: value_dic = {} value_dic['ip'] = ip li = contents['RESULT'].split("\n") # 字符串转列表 content_list = li[:len(li) - 1] # 取列表开始到倒数第二个元素,最后一个元素为空 #列表转字典 for i in content_list: key = i.split()[0].strip(':') # factor name value = i.split()[1] # factor value value_dic[key] = value if monitor_dic['SwapUsage'] == 'percentage': value_dic['SwapUsage_p'] = str(100 - int(value_dic['SwapFree']) * 100 / int(value_dic['SwapTotal'])) #real SwapUsage value value_dic['SwapUsage'] = int(value_dic['SwapTotal']) - int( value_dic['SwapFree']) MemUsage = int(value_dic['MemTotal']) - (int(value_dic['MemFree']) + int(value_dic['Buffers']) + int(value_dic['Cached'])) if monitor_dic['MemUsage'] == 'percentage': value_dic['MemUsage_p'] = str( int(MemUsage) * 100 / int(value_dic['MemTotal'])) #real MemUsage value value_dic['MemUsage'] = MemUsage value_dic['status'] = status value_dic['time'] = run_time return value_dic # if __name__ == '__main__': # for i in range(3): # host_message = {'192.168.2.128': ['root', 'oracle', 22]} # a = monitor(**host_message) # print(a)
def _get_func_in_module(plugin, func_name): mod = sys.modules[BasePlugin.get_module_name(plugin)] func = mod try: func_path = func_name.split('.') for fn in func_path: func = getattr(func, fn) except Exception as e: str(e) raise ModuleNotFoundError( 'unable found api function \'{0}\''.format(func_name)) return func
def _get_class_in_module(plugin, class_name): mod = sys.modules[BasePlugin.get_module_name(plugin)] cls = mod try: cls_path = class_name.split('.') for fn in cls_path: cls = getattr(cls, fn) except Exception as e: str(e) raise ModuleNotFoundError( 'unable found schedule class \'{0}\''.format(class_name)) return cls
def install_tables(self): # 获取模块的数据库表 module_name = BasePlugin.get_module_name(self) plugin = importlib.import_module(module_name) plugin_tables = [] for attribute_name in dir(plugin): if attribute_name.startswith('__'): continue attribute_value = getattr(plugin, attribute_name) if isinstance(attribute_value, type) and issubclass( attribute_value, pa.database.Model): plugin_tables.append(attribute_value) for table in plugin_tables: BaseDBManagerPlugin._install_table(table)
def monitor(frist_invoke=1,**kwargs): for i,v in kwargs.items(): ip = i shell_command = 'uptime' contents = BasePlugin(**kwargs).exec_shell_cmd(shell_command) run_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') # print(contents) # print(type(contents)) if contents['ERROR'] == "" : contents['ERROR'] = 0 else: contents['ERROR'] = 1 status = contents['ERROR'] if status != 0: #cmd exec error value_dic = {'status':status} else: value_dic = {} li = contents['RESULT'].split("\n") # 字符串转列表 content_list = li[:len(li) - 1] # 列表转字典 days = content_list[0].split(',')[0].split()[2] #运行天数 hours_li = content_list[0].split(',')[1].strip().split(':') #运行小时 runtime = days + '天' + hours_li[0] + '时' + hours_li[1] + '分' users = content_list[0].split(',')[2].split()[0] load1,load5,load15 = content_list[0].split('load average:')[1].split() value_dic= { 'ip':ip, 'runtime': runtime, 'users': users, 'load1': float(load1.strip(',')), 'load5': float(load5.strip(',')), 'load15': float(load15), 'time': run_time, 'status': status } return value_dic
def monitor(frist_invoke=1, **kwargs): for i, v in kwargs.items(): ip = i shell_command = "df -m | sed '1d'" contents = BasePlugin(**kwargs).exec_shell_cmd(shell_command) run_time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M') if contents['ERROR'] == "": contents['ERROR'] = 0 else: contents['ERROR'] = 1 status = contents['ERROR'] if status != 0: #cmd exec error value_dic = {'status': status} else: value_dic = {} value_dic['ip'] = ip li = contents['RESULT'].split("\n") # 字符串转列表 content_list = li[:len(li) - 1] # 取列表开始到倒数第二个元素,最后一个元素为空 #列表转字典 for i in content_list: key = i.split()[5].strip(':') # factor name 取得挂载点 value = i.split()[1:4] # factor value value_dic[key] = value value_dic['time'] = run_time value_dic['status'] = status return value_dic # if __name__ == '__main__': # kwargs={'192.168.2.112': ['root', 'oracle', 23, 'scott', 'tiger', 'prod', 1521,1]} # # kwargs={'10.10.0.2': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521],'192.168.2.128': ['root', 'qqq', 22, 'scott', 'tiger', 'prod', 1521]} # # kwargs={'192.168.2.128': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521],'192.168.2.129': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521],'10.10.0.2': ['root', 'oracle', 22, 'scott', 'tiger', 'prod', 1521]} # a=monitor(**kwargs) # print(a)
def __init__(self, socket, config, framework): BasePlugin.__init__(self, socket, config, framework) self.input_type = "" self.user_input = "" self.io = SocketIO(self._skt, "rw") self._session = None
def __init__(self, socket, config, framework): BasePlugin.__init__(self, socket, config, framework) self.input_type = None self.user_input = None self._session = None