I have C code and I want to compile and then run it with pexpect. How can I do it?? but this command is not working.
child = pexpect.spawn("gcc -o pwn code.c)
CodePudding user response:
By using this way you can see your output
In [1]: import pexpect
In [12]: pexpect.spawn("gcc ab.c")
Out[12]: <pexpect.pty_spawn.spawn at 0x7efcf4787130>
In [13]: pexpect.spawn("./a.out")
Out[13]: <pexpect.pty_spawn.spawn at 0x7efcf432d8e0>
In [14]: pexpect.spawn("./a.out").read()
Out[14]: b'Hello world'
CodePudding user response:
You can add a child.expect_exact(["$", pexpect.EOF, ])
after the pexpect.spawn
. That will move the cursor forward and execute the
command.
NOTE - Tested on Ubuntu 20.04 using Python 3.8
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, ])
Output:
Method 1:
Hello, world!
Instead of spawning two children, though, you may want to try these alternatives:
import sys
import pexpect
print("Method 2:")
child = pexpect.spawn("bash")
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())
Output:
Method 2:
$ gcc -o pwn2 code.c
$ ./pwn2
Hello, world!
$
Method 3:
Hello, world!
Process finished with exit code 0