Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Basic Python's `pexpect` usage routines in interactive process invocation
import pexpect
proc = None
def readall():
data = []
while True:
try:
proc.expect('\n')
c = proc.before
if not c: break
data.append(c)
except (pexpect.TIMEOUT, pexpect.EOF) as e:
data.append(proc.before)
break
return data
def interact(*params):
out = []
for param in params:
proc.sendline(str(param))
out.extend(readall())
out.extend(readall())
return out
def shell():
# 0x03 is a Control-C escape code.
proc.interact('\x03')
if __name__ == '__main__':
proc = pexpect.spawn(path, timeout=0.1)
# from now on, one can use:
# - readall() - to fetch all of the process' stdout (without expect pattern)
# - interact() - to send input to the process (write into it's stdin), whereas further parameters
# can be combined as follows: interact(param1, param2, ..., paramN)
# - shell() - to return fully interactive control over the process to the user
@mgeeky

This comment has been minimized.

Copy link
Owner Author

@mgeeky mgeeky commented Jan 27, 2017

Especially handy when it comes to heap-overflow or Use-After-Free exploits, since such process interaction in python may be cumbersome without proper process I/O primitives.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.