Escape arguments for paramiko.SSHClient (). Exec_command

What is the best way to escape the string for safe use as a command line argument? I know that using subprocess.Popenwill take care of this with help list2cmdline(), but it doesn't seem to work correctly for paramiko. Example:

from subprocess import Popen
Popen(['touch', 'foo;uptime']).wait()

This creates a file with the literal name foo;uptimethat I want. For comparison:

from paramiko import SSHClient()
from subprocess import list2cmdline
ssh = SSHClient()
#... load host keys and connect to a server
stdin, stdout, stderr = ssh.exec_command(list2cmdline(['touch', 'foo;uptime']))
print stdout.read()

Creates a file with a name fooand prints the runtime of the remote host. He performed uptimeas the second command instead of using it as part of the argument of the first team touch. This is not what I want.

I tried to escape with a backslash semicolon before and after sending it to list2cmdline, but then I ended up in a file with a name foo\;uptime.

, , uptime :

stdin, stdout, stderr = ssh.exec_command(list2cmdline(['touch', 'foo;echo test']))
print stdout.read()

, foo;echo test, list2cmdline .

, pipes.quote() , list2cmdline.

EDIT: , , , , , , ;, &, .

+3
3

, POSIX, :

def shell_escape(arg):
    return "'%s'" % (arg.replace(r"'", r"'\''"), )

?

POSIX :

('') . .

, . - , , . ( '), (\'), ( ').

?

POSIX. bash. Solaris 5.10 /bin/sh (, , POSIX, ), , .

, . , ssh ( /etc/passwd ). , , /usr/bin/python git-shell - , , , -, , , .

csh/tcsh

, tcsh, , paramiko exec_command . ( /usr/bin/python , , ...)

tcsh, , . , , . , , tcsh :

$ tcsh -c $'echo \'foo\nbar\''
Unmatched '.
Unmatched '.

, , , , tcsh ( , , , , ,...).

, , :

  • (\n, \t,...)
  • (', ", \)
  • (*, ?, [] ..)
  • (|, &, ||, &&,...)
  • Newlines

. re.escape - -- , POSIX escape- (, Python, "\\\n") - , . , re.escape , -, , . , , re.escape (, ) API.

, escape- , - , , , . printf "%s\n" escaped-string-to-test, , . echo : echo \n. /bin/echo , Solaris 5.10, , , \n.

+9

list2cmdline(), Microsoft, , POSIX, SSH.

Python pipes.quote() , . SSH:

from pipes import quote
command = ['touch', 'foo;uptime']
print ' '.join(quote(s) for s in command)

;:

touch 'foo;uptime'
0

re.escape() - , .

. * (** *)

** * ...

:

from paramiko import SSHClient()
from subprocess import list2cmdline
import re
ssh = SSHClient()
#... load host keys and connect to a server
stdin, stdout, stderr = ssh.exec_command(' '.join(['touch', re.escape('foo;uptime')]))

foo;uptime, .

- , , :

stdin, stdout, stderr = ssh.exec_command(' '.join(['touch', re.escape('test;rm foo&echo "Uptime: `uptime`"')]))
-3
source

Source: https://habr.com/ru/post/1752755/


All Articles