要执行该命令,您可能需要通过在pexpect.spawn 之后添加child.expect_exact() 来将pexpect 光标向前移动:
注意 - 使用 Python 3.8 在 Ubuntu 20.04 上测试
import sys
import pexpect
print("Method 1:")
child = pexpect.spawn("gcc -o pwn code.c")
child.logfile_read = sys.stdout.buffer
child.expect_exact(["$", pexpect.EOF, ])
child = pexpect.spawn("./pwn")
child.logfile_read = sys.stdout.buffer
child.expect_exact(["$", pexpect.EOF, ])
输出:
Method 1:
Hello, world!
但是,您可能想尝试这些替代方案,而不是生成两个孩子;在您的情况下,由于您不需要保持子进程处于打开状态,因此我建议使用方法 3,使用 pexpect.run:
import sys
import pexpect
print("Method 2:")
child = pexpect.spawn("bash")
# Shows all output
child.logfile_read = sys.stdout.buffer
child.expect_exact("$")
child.sendline("gcc -o pwn2 code.c")
child.expect_exact("$")
child.sendline("./pwn2")
child.expect_exact("$")
child.close()
print("Method 3:")
list_of_commands = ["gcc -o pwn3 code.c",
"./pwn3", ]
for c in list_of_commands:
command_output, exitstatus = pexpect.run(c, withexitstatus=True)
if exitstatus != 0:
print("Houston, we've had a problem.")
print(command_output.decode().strip())
输出:
Method 2:
$ gcc -o pwn2 code.c
$ ./pwn2
Hello, world!
$
Method 3:
Hello, world!
Process finished with exit code 0