在Python 3中执行bash命令

时间:2019-05-19 20:32:55

标签: python python-3.x bash subprocess

我有一个服务器程序,可以接受来自客户端的命令。服务器最终接收到的命令可能类似于:

ls -al | grep cats >> file.txt

我想在服务器上运行收到的命令。目前,我一直在通过subprocess模块进行尝试:

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
# ...

当命令是ifconfig之类的命令时,此方法工作正常,但是当使用带有管道,IO重定向或目录更改的任何命令时,此命令似乎崩溃了。例如,运行ls -al | grep cats >> file.txt示例将导致:

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

执行通过Python3提供的示例之类的命令的最佳解决方案是什么?本质上,我希望能够与服务器计算机进行交互,就像客户端与服务器之间存在开放的SSH会话一样。

我希望不必手动解析命令并搜索管道/ IO重定向等,然后多次调用subprocess.Popen

0 个答案:

没有答案