python 使用 paramiko 检查远程主机上是否存在路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/850749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:58:42  来源:igfitidea点击:

Check whether a path exists on a remote host using paramiko

pythonsshscpparamiko

提问by Sridhar Ratnakumar

Paramiko's SFTPClientapparently does not have an existsmethod. This is my current implementation:

ParamikoSFTPClient显然没有exists方法。这是我目前的实现:

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.

有一个更好的方法吗?检查异常消息中的子字符串非常难看,而且可能不可靠。

回答by Matt Good

See the errnomodulefor constants defining all those error codes. Also, it's a bit clearer to use the errnoattribute of the exception than the expansion of the __init__args, so I'd do this:

有关定义所有这些错误代码的常量,请参阅errno模块。此外,使用errno异常的属性比扩展__init__args更清晰一些,所以我会这样做:

except IOError, e: # or "as" if you're using Python 3.0
  if e.errno == errno.ENOENT:
    ...

回答by JimB

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

没有为 SFTP(不仅仅是 paramiko)定义“存在”方法,所以你的方法很好。

I think checking the errno is a little cleaner:

我认为检查 errno 更简洁:

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

回答by jslay

Paramiko literally raises FileNotFoundError

Paramiko 字面上提出 FileNotFoundError

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