ssh: fix quoting of platform_command

The old code was constructing the shell command like this:

  echo -e """%s""" | python

However, shells don't do triple quoting like Python. What happens
instead is that the first pair of quotes become an empty string and
disappears. The second set of quotes quote the Python code and the
third pair of quotes also disappear.

To correctly quote the argument, one should instead wrap it in
single-quotes and take care to replace internal single-quotes with an
escaped version that first ends the previously quoted string, inserts
a single-quote and begins a new quoted string. The new shellquote
function does this.

When using this function, the -e flag is not needed or desired: it
will prematurely evaluate escape sequences that would otherwise have
been evaluated by Python.

Change-Id: I19166575b0d9b9e9836d072abab8ce0fbb2af7f2
Closes-Bug: 1401542
This commit is contained in:
Martin Geisler 2014-12-11 15:12:22 +01:00
parent dea382bae1
commit f0e97f6e71
1 changed files with 13 additions and 1 deletions

View File

@ -51,6 +51,18 @@ TTY_REQUIRED = [
]
def shellquote(s):
r"""Quote a string for use on a command line.
This wraps the string in single-quotes and converts any existing
single-quotes to r"'\''". Here the first single-quote ends the
previous quoting, the escaped single-quote becomes a literal
single-quote, and the last single-quote quotes the next part of
the string.
"""
return "'%s'" % s.replace("'", r"'\''")
def make_pkey(private_key):
"""Return a paramiko.pkey.PKey from private key string."""
key_classes = [paramiko.rsakey.RSAKey,
@ -179,7 +191,7 @@ class SSH(paramiko.SSHClient): # pylint: disable=R0902
utils.get_platform_info)
platform_command += ("\nsys.stdout.write(str("
"get_platform_info()))\n")
command = 'echo -e """%s""" | python' % platform_command
command = 'echo %s | python' % shellquote(platform_command)
output = self.remote_execute(command)
stdout = re.split('\n|\r\n', output['stdout'])[-1].strip()
if stdout: