在 sftp 之前检查远程机器上是否存在目录

新手上路,请多包涵

这是我的函数,它使用 paramiko 将文件从本地机器复制到远程机器,但它不检查目标目录是否存在并继续复制,如果远程路径不存在则不会抛出错误

def copyToServer(hostname, username, password, destPath, localPath):
    transport = paramiko.Transport((hostname, 22))
    transport.connect(username=username, password=password)
    sftp = paramiko.SFTPClient.from_transport(transport)
    sftp.put(localPath, destPath)
    sftp.close()
    transport.close()

我想检查远程机器上的路径是否存在,如果不存在则抛出错误。

提前致谢

原文由 Niati Arora 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.7k
2 个回答

这会做

def copyToServer(hostname, username, password, destPath, localPath):
    transport = paramiko.Transport((hostname, 22))

    sftp = paramiko.SFTPClient.from_transport(transport)
    try:
        sftp.put(localPath, destPath)
        sftp.close()
        transport.close()
        print(" %s    SUCCESS    " % hostname )
        return True

    except Exception as e:
        try:
            filestat=sftp.stat(destPath)
            destPathExists = True
        except Exception as e:
            destPathExists = False

        if destPathExists == False:
        print(" %s    FAILED    -    copying failed because directory on remote machine doesn't exist" % hostname)
        log.write("%s    FAILED    -    copying failed    directory at remote machine doesn't exist\r\n" % hostname)
        else:
        print(" %s    FAILED    -    copying failed" % hostname)
        log.write("%s    FAILED    -    copying failed\r\n" % hostname)
        return False

原文由 Gurpreet sandhu 发布,翻译遵循 CC BY-SA 4.0 许可协议

在我看来,最好避免异常,所以除非你有很多文件夹,否则这对你来说是个不错的选择:

 if folder_name not in self.sftp.listdir(path):
    sftp.mkdir(os.path.join(path, folder_name))

原文由 Rotem Shaanan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题