Skip to content

Instantly share code, notes, and snippets.

@mgeeky
Created January 27, 2017 17:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mgeeky/def74cb10301b2d733e5952b9118680e to your computer and use it in GitHub Desktop.
Save mgeeky/def74cb10301b2d733e5952b9118680e to your computer and use it in GitHub Desktop.
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
Copy link
Author

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