Python: subprocess call with shell=False not working

后端 未结 4 1755
孤街浪徒
孤街浪徒 2020-12-01 16:57

I am using Python script to invoke a Java virtual machine. The following command works:

subprocess.call([\"./rvm\"], shell=False)  # works
subprocess.call([\         


        
4条回答
  •  有刺的猬
    2020-12-01 17:06

    If you want to use shell=True, this is legit, otherwise it would have been removed from the standard library. The documentation doesn't say to avoid it, it says:

    Executing shell commands that incorporate unsanitized input from an untrusted source makes a program vulnerable to shell injection, a serious security flaw which can result in arbitrary command execution. For this reason, the use of shell=True is strongly discouraged in cases where the command string is constructed from external input.

    But in your case you are not constructing the command from user input, your command is constant, so your code doesn't present the shell injection issue. You are in control of what the shell will execute, and if your code is not malicious per se, you are safe.

    Example of shell injection

    To explain why the shell injection is so bad, this is the example used in the documentation:

    >>> from subprocess import call
    >>> filename = input("What file would you like to display?\n")
    What file would you like to display?
    non_existent; rm -rf / #
    >>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
    

    Edit

    With the additional information you have provided editing the question, stick to Padraic's answer. You should use shell=True only when necessary.

提交回复
热议问题