I have a server program that accepts commands from a client. The server ends up receiving commands that might be something like:
ls -al | grep cats >> file.txt
I'd like to run the received command on the server. Currently I've been trying this via the subprocess
module:
command = "ls -al | grep cats >> file.txt" # for demonstration purposes - I'm actually getting the command through using raw sockets and the command is encrypted initially
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
output, error = process.communicate()
# ...
# output of the command will be sent back to the client machine now
# ...
This works fine when the command is something like ifconfig
, but seems to break down when anything with pipes, IO redirection, or directory changes are used. For instance, running the ls -al | grep cats >> file.txt
example results in:
ls: cannot access '|' No such file or directory
ls: cannot access 'grep' No such file or directory
ls: cannot access 'cats' No such file or directory
ls: cannot access '>>' No such file or directory
ls: cannot access 'file.txt' No such file or directory
What's a good solution to execute a command like the example provided via Python3? Essentially I'd like to be able to interact with the server machine as if the client had an open SSH session with the server.
I'm hoping that I don't have to manually parse the commands and search for pipes/IO redirection, etc. and then make multiple calls to subprocess.Popen