Search code examples
pythonpython-2.7python-3.xparamiko

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


Solution

  • 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