Created
January 27, 2017 17:34
-
-
Save mgeeky/def74cb10301b2d733e5952b9118680e to your computer and use it in GitHub Desktop.
Basic Python's `pexpect` usage routines in interactive process invocation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.