import re import subprocess import tempfile import os import pexpect def do_worker(str_instruction): try: # 使用 subprocess 执行 shell 命令 result = subprocess.run(str_instruction, shell=True, text=True,capture_output=True) return { "returncode": result.returncode, "stdout": result.stdout, "stderr": result.stderr } except Exception as e: return {"error": str(e)} def do_worker_ftp_pexpect(str_instruction): # 解析指令 lines = str_instruction.strip().split('\n') cmd_line = lines[0].split('<<')[0].strip() # 提取 "ftp -n 192.168.204.137" inputs = [line.strip() for line in lines[1:] if line.strip() != 'EOF'] # 使用 pexpect 执行命令 child = pexpect.spawn(cmd_line) for input_line in inputs: child.expect('.*') # 等待任意提示 child.sendline(input_line) # 发送输入 child.expect(pexpect.EOF) # 等待命令结束 output = child.before.decode() # 获取输出 child.close() return output def do_worker_ftp_script(str_instruction): # 创建临时文件保存输出 with tempfile.NamedTemporaryFile(delete=False) as tmpfile: output_file = tmpfile.name # 构建并执行 script 命令 script_cmd = f"script -c '{str_instruction}' {output_file}" result = subprocess.run(script_cmd, shell=True, text=True) # 读取输出文件内容 with open(output_file, 'r') as f: output = f.read() # 删除临时文件 os.remove(output_file) return output if __name__ == "__main__": # 示例使用 str_instruction = """ ftp -n 192.168.204.137 << EOF user anonymous anonymous@example.com ls bye EOF """ output = do_worker(str_instruction) print(f"*****\n{output}\n*****") output = do_worker_ftp_script(str_instruction) lines = output.splitlines() # 跳过第一行(Script started)和最后一行(Script done) ftp_output = lines[1:-1] strout = '\n'.join(ftp_output) print("111111111") print(strout)