Last active
December 6, 2022 21:22
-
-
Save Hermann-SW/65e07365cc2586b76afb6274ece12d5b to your computer and use it in GitHub Desktop.
Remote control bash from Python
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
from subprocess import Popen, PIPE | |
from sys import argv | |
import re | |
stop = "qwertz1234567890ufugUUGUGUgUgUGuGFzR775§%!=%%54321rUF/Rtt8t8TTT4§2hj\n" | |
bye = ["tschüs","do_widzenia","ahoj","ciao","salut","adieu","vaarwel","farvel"] | |
byes = re.sub(r"['[]]*", "", str(bye)) | |
cmd = "bash" if len(argv) == 1 else argv[1] | |
p = Popen(cmd, stdin=PIPE, stdout=PIPE) | |
while True: | |
i = input(cmd + ": ") | |
if i in bye: break | |
if i == "?": | |
print("'cmd' gets executed\n'?' for this help\nto exit, any of: "+byes) | |
continue | |
p.stdin.write(bytes(i + "\necho " + stop, 'utf-8')); p.stdin.flush() | |
while True: | |
resp = p.stdout.readline().decode(encoding="utf-8") | |
if resp == stop: break | |
print(resp, end="") |
If responses are known to be 1 line always, much simpler bash1.py can be used:
https://gist.github.com/Hermann-SW/4c5b204f2eecf712b568bf85ee111a2b
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Popen communicate() is no option for this application.
All .poll() code I found did not do what is needed.
That is the reason this script uses the "stop" line trick for dealing with multi line responses:
'?' help is builtin, exit of bash_.py with German "tschüs",
or any of the Germany neighbor country's languages word for "bye" (in clockwise map order):
Long responses just work: