Python的子进程不工作按预期find命令

问题描述 投票:2回答:5

我试图找出蟒蛇的节点上孤立文件。下面的代码片段

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

python linux subprocess
5个回答
2
投票

只需添加壳=真到你check_output

s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o", "\( -nouser -o -nogroup \)", "-print"], shell=True)

2
投票

你应该在每个空格分开的命令。要做到这一点,最简单的方法是使用shlex.split

import shlex
import subprocess

cmd = shlex.split('find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print')
subprocess.check_output(cmd)

1
投票

我想你的脚本,并像你一样得到了同样的错误。我尝试不同的东西,发现东西为我工作。我变了

-print

-exec

和它的工作。但我不知道这是为什么的行为。


1
投票

您可以设置shell=True选项,然后只传递整个shell命令。我想空白导致了问题。

s = subprocess.check_output("find / -fstype proc -prune -o \( -nouser -o -nogroup \) -print", shell=True)

注意this warning与设置shell=True。如果输入来自外部源(如用户输入)基本上不这样做。在这种情况下,它应该因此被罚款。


0
投票

每个命令行参数必须作为一个单独的列表项,包括括号及其内容进行传递:

s = subprocess.check_output(["find", "/", "-fstype", "proc", "-prune", "-o",
                            "(", "-nouser", "-o", "-nogroup", ")", 
                            "-print"])
© www.soinside.com 2019 - 2024. All rights reserved.