【问题标题】:check if directory exists on remote machine before sftp在 sftp 之前检查远程机器上是否存在目录
【发布时间】:2017-02-08 05:53:11
【问题描述】:

这是我的函数,它使用 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() 

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

提前致谢

【问题讨论】:

    标签: python python-2.7 python-3.x paramiko


    【解决方案1】:

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

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

    【讨论】:

      【解决方案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
      

      【讨论】:

        【解决方案3】:

        您可以使用SFTPClientchdir() 方法。它检查远程路径是否存在,如果不存在则引发错误。

        try:
            sftp.chdir(destPath)
        except IOError as e:
            raise e
        

        【讨论】:

        【解决方案4】:

        我会在 SFTPClient 中使用 listdir 方法。您可能必须递归地使用它来确保整个路径有效。

        【讨论】:

          猜你喜欢
          • 2012-06-13
          • 1970-01-01
          • 2015-07-26
          • 1970-01-01
          • 1970-01-01
          • 2020-03-22
          • 2015-01-29
          • 1970-01-01
          • 2011-08-20
          相关资源
          最近更新 更多