import pexpect from tools.ToolBase import ToolBase class NcTool(ToolBase): def validate_instruction(self, instruction): timeout = 60 #指令过滤 if "<<<" in instruction: instruction = f"bash -c \"{instruction}\"" return instruction,timeout def do_worker_pexpect(self,str_instruction,timeout,ext_params): try: result = "" exc_do = pexpect.spawn('bash',['-c',str_instruction],timeout=timeout,encoding='utf-8')#spawn 第一个参数是可执行文件 while True: index = exc_do.expect([ pexpect.TIMEOUT, pexpect.EOF, 'Password:' ]) result += str(exc_do.before) if index == 0: result += f"\n执行超时{timeout}秒" break elif index == 1: break elif index == 2: result += "Password:\n" exc_do.sendline('') # 输入空密码后不知道会有多少种情况,密码不对,密码对 continue else: print("遇到其他输出!") break return result except Exception as e: return f"执行错误: {str(e)}" def execute_instruction(self, instruction_old): ext_params = self.create_extparams() # 第一步:验证指令合法性 instruction,time_out = self.validate_instruction(instruction_old) if not instruction: return False, instruction_old, "该指令暂不执行!","",ext_params # 过滤修改后的指令是否需要判重?同样指令再执行结果一致?待定---#? # 第二步:执行指令---需要对ftp指令进行区分判断 #output = self.do_worker_script(instruction, time_out, ext_params) output = self.do_worker_pexpect(instruction, time_out, ext_params) # 第三步:分析执行结果 analysis = self.analyze_result(output,instruction,"","") return True, instruction, analysis,output,ext_params def analyze_result(self, result,instruction,stderr,stdout): #指令结果分析 return result