Evaluating a remote (Paramiko) ssh command's output into a success/failure boolean Evaluating a remote (Paramiko) ssh command's output into a success/failure boolean shell shell

Evaluating a remote (Paramiko) ssh command's output into a success/failure boolean


You can use ast.literal_eval(). This is safer than eval() because it only evaluates literals, not arbitrary expressions.


A filename should always be quoted before including it in a context where it might be parsed as code.

Here, we're using the technique introduced in How can you get the SSH return code using Paramiko? to retrieve exit status directly from the SSH channel, with no need to parse any string passed over stdout.

try:  from pipes import quote  # Python 2.xexcept ImportError:  from shlex import quote  # Python 3.xdef test_remote_existance(filename):    # assuming that "ssh" is a paramiko SSHClient object    command = 'test -e {0} </dev/null >/dev/null 2>&1'.format(quote(remote_file))    chan = ssh.get_transport().open_session()    chan.exec_command(command)    return chan.recv_exit_status() == 0


To test a file existence over SSH, use the standard API – SFTP, instead of running shell commands.

With Paramiko you can do that by:

sftp = ssh.open_sftp()try:    sftp.stat(path)    print("File exists")except IOError:    print("File does not exist or cannot be accessed")