Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check whether a path exists on a remote host using paramiko

Paramiko's SFTPClient apparently does not have an exists method. This is my current implementation:

def rexists(sftp, path):
    """os.path.exists for paramiko's SCP object
    """
    try:
        sftp.stat(path)
    except IOError, e:
        if 'No such file' in str(e):
            return False
        raise
    else:
        return True

Is there a better way to do this? Checking for substring in Exception messages is pretty ugly and can be unreliable.

like image 570
Sridhar Ratnakumar Avatar asked May 12 '09 01:05

Sridhar Ratnakumar


1 Answers

See the errno module for constants defining all those error codes. Also, it's a bit clearer to use the errno attribute of the exception than the expansion of the __init__ args, so I'd do this:

except IOError, e: # or "as" if you're using Python 3.0
  if e.errno == errno.ENOENT:
    ...
like image 198
Matt Good Avatar answered Sep 23 '22 15:09

Matt Good