Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/300.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Bash:使用shell规则标记字符串,而不使用eval';你是说什么?_Python_Bash_Eval_Shlex - Fatal编程技术网

Python Bash:使用shell规则标记字符串,而不使用eval';你是说什么?

Python Bash:使用shell规则标记字符串,而不使用eval';你是说什么?,python,bash,eval,shlex,Python,Bash,Eval,Shlex,我正在写一个包装器脚本。原始程序的参数位于单独的文件中,args。脚本需要使用shell参数规则拆分args的内容,然后运行程序。部分解决方案(set+eval)提供于: 但是在我的例子中,args是用户生成的。很容易想象 args:echo“Hello,'world'!$(rm-rf/)”(不酷,但无害:命令在例如docker容器中运行) args:bash-c“$JAVA\u HOME/>&&”(有害:$JAVA\u HOME原本是环境变量JAVA\u HOME的容器的值,但实际上会在ev

我正在写一个包装器脚本。原始程序的参数位于单独的文件中,
args
。脚本需要使用shell参数规则拆分
args
的内容,然后运行程序。部分解决方案(
set
+
eval
)提供于:

但是在我的例子中,
args
是用户生成的。很容易想象

  • args
    echo“Hello,'world'!$(rm-rf/)”
    (不酷,但无害:命令在例如docker容器中运行)
  • args
    bash-c“$JAVA\u HOME/>&&”
    (有害:
    $JAVA\u HOME
    原本是环境变量
    JAVA\u HOME
    容器的值,但实际上会在
    eval
    调用包装器脚本子shell中的命令时被替换。)
我试过Python,这很管用:

#!/usr/bin/env python
import shlex, subprocess, sys

with open('args', 'r') as argsfile:
    args = argsfile.read()

with open(sys.argv[1], 'w') as outfile, open(sys.argv[2], 'w') as errfile:
    exit(subprocess.call(["run_in_container"] + shlex.split(args), stdout=outfile, stderr=errfile))

在bash中是否有方法执行
shlex
:使用shell参数规则标记字符串,但不要替换任何变量的值,不要执行
$(…)
等?

我怀疑这是否(容易且安全)可行,我甚至会说,沿着这条路走是个坏主意。当有一个完全可以接受的Python脚本来完成这项工作时,使用bash是个坏主意?也许是这样,但我只是好奇在Bash中是否可能,如果用户确定了参数,那么如何阻止它们传入
rm-rf/
?什么都没有。该命令将在隔离的环境中运行,例如docker容器,因此这不是问题所在。问题在于将变量意外替换为“args”。我怀疑这是否(容易且安全)可行,我甚至认为沿着这条路走是个坏主意。如果有一个完全可以接受的Python脚本来执行此操作,那么使用bash是个坏主意?也许是这样,但我只是好奇在Bash中是否可能,如果用户确定了参数,那么如何阻止它们传入
rm-rf/
?什么都没有。该命令将在隔离的环境中运行,例如docker容器,因此这不是问题所在。问题在于意外地将变量替换为“args”。
#!/usr/bin/env python
import shlex, subprocess, sys

with open('args', 'r') as argsfile:
    args = argsfile.read()

with open(sys.argv[1], 'w') as outfile, open(sys.argv[2], 'w') as errfile:
    exit(subprocess.call(["run_in_container"] + shlex.split(args), stdout=outfile, stderr=errfile))