Check whether a path exists on a remote host using paramiko Check whether a path exists on a remote host using paramiko python python

Check whether a path exists on a remote host using paramiko


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:    ...


Paramiko literally raises FileNotFoundError

def sftp_exists(sftp, path):    try:        sftp.stat(path)        return True    except FileNotFoundError:        return False


There is no "exists" method defined for SFTP (not just paramiko), so your method is fine.

I think checking the errno is a little cleaner:

def rexists(sftp, path):    """os.path.exists for paramiko's SCP object    """    try:        sftp.stat(path)    except IOError, e:        if e[0] == 2:            return False        raise    else:        return True