Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if directory exists on remote machine before sftp

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

like image 339
Niati Arora Avatar asked Oct 23 '25 21:10

Niati Arora


2 Answers

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))
like image 186
Rotem Shaanan Avatar answered Oct 26 '25 10:10

Rotem Shaanan


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
like image 20
Gurpreet sandhu Avatar answered Oct 26 '25 11:10

Gurpreet sandhu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!