我试图找出蟒蛇的节点上孤立文件。下面的代码片段
#!/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")
当我尝试运行此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]
当我在命令行运行相同的命令时,它工作正常。
> find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print
/root/a
几个你建议使用shell =真,按蟒蛇文档的子它是安全隐患。 Warning Using shell=True can be a security hazard.
只需添加壳=真到你check_output
s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o", "\( -nouser -o -nogroup \)", "-print"], shell=True)
你应该在每个空格分开的命令。要做到这一点,最简单的方法是使用shlex.split
:
import shlex
import subprocess
cmd = shlex.split('find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print')
subprocess.check_output(cmd)
我想你的脚本,并像你一样得到了同样的错误。我尝试不同的东西,发现东西为我工作。我变了
-print
至
-exec
和它的工作。但我不知道这是为什么的行为。
您可以设置shell=True
选项,然后只传递整个shell命令。我想空白导致了问题。
s = subprocess.check_output("find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print", shell=True)
注意this warning与设置shell=True
。如果输入来自外部源(如用户输入)基本上不这样做。在这种情况下,它应该因此被罚款。
每个命令行参数必须作为一个单独的列表项,包括括号及其内容进行传递:
s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o",
"(", "-nouser", "-o", "-nogroup", ")",
"-print"])