0

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

ChristianF
  • 1,735
  • 4
  • 28
  • 56
  • 1
    You didn't use a shell (such as bash). Pass `shell=True` for that. But this is almost certainly an inadvisable thing to do; is there anything to make this connection more trustworthy than an ssh session? – Yann Vernier May 19 '19 at 20:35
  • @Yann: SSH can be made secure (e.g. by only allowing public key authentication plus a second factor). I suspect that what the OP is proposing here is significantly *less* trustworthy than SSH would be. – Daniel Pryden May 19 '19 at 20:39
  • Key based authentication could be used - but this is just a proof of concept for part of a backdoor program. None of this will be used in a production code base or anything like that. Just for learning purposes – ChristianF May 19 '19 at 20:41
  • @121c: This *exact* situation is described in section [Replacing shell pipeline](https://docs.python.org/3/library/subprocess.html#replacing-shell-pipeline) in the Python `subprocess` module documentation. – Daniel Pryden May 19 '19 at 20:41

0 Answers0