def on_message(self, message): data = json.loads(message) pattern = data.get('pattern', '') command = data.get('command', '') asset_name_str = '' if pattern and command: for inv in self.runner.inventory.get_hosts(pattern=pattern): asset_name_str += '%s ' % inv.name self.write_message('匹配主机: ' + asset_name_str) self.write_message( '<span style="color: yellow">Ansible> %s</span>\n\n' % command) self.__class__.tasks.append( MyThread(target=self.run_cmd, args=(command, pattern))) ExecLog(host=asset_name_str, cmd=command, user=self.user.username, remote_ip=self.remote_ip).save() for t in self.__class__.tasks: if t.is_alive(): continue try: t.setDaemon(True) t.start() except RuntimeError: pass
def run_cmd(self, command, pattern): self.runner.run('shell', command, pattern=pattern) ExecLog(host=self.asset_name_str, cmd=self.command, user=self.user.username, remote_ip=self.remote_ip, result=self.runner.results).save() newline_pattern = re.compile(r'\n') for k, v in self.runner.results.items(): for host, output in v.items(): output = newline_pattern.sub('<br />', output) if k == 'ok': header = "<span style='color: green'>[ %s => %s]</span>\n" % (host, 'Ok') else: header = "<span style='color: red'>[ %s => %s]</span>\n" % (host, 'failed') self.write_message(header) self.write_message(output) self.write_message('\n~o~ Task finished ~o~\n')