Skip to content

Instantly share code, notes, and snippets.

@luc99a
Created August 27, 2014 09:06
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 luc99a/0337bf7b4aed55015094 to your computer and use it in GitHub Desktop.
Save luc99a/0337bf7b4aed55015094 to your computer and use it in GitHub Desktop.
Shell class in Python executes a single /bin/bash subprocess and gives to it commands writing on stdin. Needs improovment
#Hi this class spawns a single subprocess /bin/bash and pass commands to it's stdin, this means that you can also
#execute cd commands here is an example that prints the /etc/passwd file and then echoes "Done"
#the class is only a proof of concept and has to be improoved
#for example the get_beffered_output() could not give the entire output of the command we executed depending on how much time the
#command uses to end
import subprocess
import threading
import time
class Shell:
def __init__(self):
self.process = subprocess.Popen(["/bin/bash"], stdout = subprocess.PIPE, stdin = subprocess.PIPE)
self.reader_thread = threading.Thread(target = self.read)
self.buffer = []
self.running = True
self.reader_thread.start()
def execute(self, command):
self.process.stdin.write(command.strip("\n") + "\n")
def get_buffered_output(self):
time.sleep(2)
buffer = self.buffer
self.buffer = []
return "".join(buffer)
def read(self):
while self.running:
line = self.process.stdout.readline()
self.buffer.append(line)
def close(self):
self.running = False
self.execute("exit")
shell = Shell()
shell.execute("cd /")
shell.execute("cd etc")
shell.execute("cat passwd")
shell.execute("echo Done")
print shell.get_buffered_output()
shell.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment