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

check if directory exists on remote machine before 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() 

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

提前致谢

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

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

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

这样就可以了

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

我认为最好避免出现异常,因此除非您有很多文件夹,否则这对您来说是个不错的选择:

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