why are '(single quote) or \"(double quote) no

2019-08-15 22:17发布

问题:

I am using subprocess.check_output() method to execute commands from within the python script.

There are some commands that need "(double quotes) to be present in syntax. Here's one example:

>drozer console connect -c "run app.package.info -a com.package.name"

It throws error if we remove "(double quotes) from above command.

I did the following :

string = '\"run app.package.info -a com.package.name\"'
command = ['/usr/bin/drozer','console','connect','-c',string]
output = subprocess.check_output(command)

This yields me to error:

*** Unknown syntax: "run app.package.info  -a com.package.name"

Please Note : commands without quotes are running through subprocess.check_output, so code works properly.

How can I solve this issue of quotes? Any help would be highly appreciated.

Thanks

回答1:

You don’t need the double quotes.

The reason you need them with the shell command is that the shell is parsing the command line from a string, and it uses them as an indication that the text run app.package.info -a com.package.name should be placed in a single argument:

#!/usr/bin/env python
import subprocess

c_arg = 'run app.package.info -a com.package.name'
command = ['/usr/bin/drozer', 'console', 'connect', '-c', c_arg]
output = subprocess.check_output(command)
print("Got %r" % (output,))

When you’re using code to start a process, you explicitly specify individual arguments, and no shell parsing is going on, so there’s no need for the extra quotes.



回答2:

You could try to use the option shell=True like:

output = subprocess.check_output(command, shell=True)


回答3:

To solve your problem you need a split method that understands subprocess command argument requirements. Use shlex like:

>>> import shlex
>>> import subprocess
>>> 
>>> command = 'drozer console connect -c "run app.package.info -a com.package.name"'
>>> command = shlex.split(command)
>>> command
['drozer', 'console', 'connect', '-c', 'run app.package.info -a com.package.name']
>>> output = subprocess.check_output(command)


回答4:

Find more info on drozer commands and more on http://th3-incognito-guy.blogspot.in/2014/09/drozer-security-attack-framework-for.html