I'm trying to send a command through a socket from client to server to execute a command on the server and send the output back to me. Everything works fine if the command is one word with no options. However if I use an option such as netstat -an or dir c:\\
then the command isn't recognized and from the output it looks like quotes are put around the command before being executed ( '"netstat -an"'
is not recognized as an internal or external command). I know they aren't saved in the variable this way because I printed it before being executed to error check. Please help. Here is what my code looks like:
commout = subprocess.Popen([data], stdout=subprocess.PIPE, shell=True)
(out, err) = commout.communicate()
Try make data
an array of arguments (the first being the actual command).
For example:
commout = subprocess.Popen(['netstat', '-an'], stdout=subprocess.PIPE, shell=True)
The first element is a string representing the actual command ( netstat
), the next element is a string representing the first argument ( -an
).
To clarify, Popen(['echo', 'a', 'b']
is equivalent to echo ab
on the command line, whereas Popen(['echo', 'a b']
would be equivalent to echo "ab"
instead (ie. a single argument with a space between a
and b
.
If you pass a list, each item in it will be quoted separately. In this case, just pass a string:
subprocess.Popen(data, stdout=subprocess.PIPE, shell=True)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.