[英]Python subprocess is not working as expected for find command
I am trying to find out orphan files on the node in python. 我试图在python的节点上找出孤立的文件。 Below is the code snippet 下面是代码片段
#!/usr/bin/python
import subprocess
try:
s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o", "\( -nouser -o -nogroup \)", "-print"])
except subprocess.CalledProcessError as e:
print e.output
else:
if len(s) > 0:
print ("List of Orphan Files are \n%s\n" % s)
else:
print ("Orphan Files does not Exists on the NE")
When I try to run this python code 当我尝试运行此python代码时
> python test.py
find: paths must precede expression: \( -nouser -o -nogroup \)
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
When I run the same command on CLI it is working fine. 当我在CLI上运行相同的命令时,它工作正常。
> find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print
/root/a
Few of you suggested to use shell=true, as per the python doc for subprocess it is security hazard. 很少有人建议使用shell = true,因为根据python doc对于子进程的使用,这是安全隐患。 Warning Using shell=True can be a security hazard.
只需将shell = True添加到您的check_output
s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o", "\( -nouser -o -nogroup \)", "-print"], shell=True)
You should split the command on every whitespace. 您应该在每个空白处分割命令。 The easiest way to do this is with shlex.split
: 最简单的方法是使用shlex.split
:
import shlex
import subprocess
cmd = shlex.split('find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print')
subprocess.check_output(cmd)
You can set the shell=True
option and then just pass the entire shell command. 您可以设置shell=True
选项,然后仅传递整个shell命令。 I think the whitespace is causing the issue. 我认为空白导致了问题。
s = subprocess.check_output("find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print", shell=True)
Note this warning relating to setting shell=True
. 注意此警告与设置shell=True
。 Basically don't do it if the input comes from an external source (like user input). 如果输入来自外部源(例如用户输入),则基本上不执行此操作。 In this case it should therefore be fine. 因此,在这种情况下应该没问题。
I tried your script and got the same error as you did. 我尝试了您的脚本,并得到了与您相同的错误。 I was trying different things and found something that worked for me. 我尝试了不同的事情,发现了一些对我有用的东西。 I changed 我变了
-print
to 至
-exec
and it worked. 而且有效。 But I am not sure why this was the behavior. 但是我不确定为什么会这样。
Each command line parameter must be passed as a separate list item, including the parentheses and their contents: 每个命令行参数都必须作为一个单独的列表项传递,包括括号及其内容:
s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o",
"(", "-nouser", "-o", "-nogroup", ")",
"-print"])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.