check if directory exists on remote machine before sftp

10,854

Solution 1

This will do

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

Solution 2

In my opinion it's better to avoid exceptions, so unless you have lots of folders, this is a good option for you:

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

Solution 3

You can use the chdir() method of SFTPClient. It checks if the remote path exists, raises error if not.

try:
    sftp.chdir(destPath)
except IOError as e:
    raise e
Share:
10,854
Niati Arora
Author by

Niati Arora

Updated on July 27, 2022

Comments

  • Niati Arora
    Niati Arora almost 2 years

    this my function that copies file from local machine to remote machine with paramiko, but it doesn't check if the destination directory exists and continues copying and doesn't throws error if remote path doesn't exists

    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() 
    

    i want to check if path on remote machine exists and throw error if not.

    thanks in advance