1

I'm trying to read a latestfile from the sftp server using python but it shows the error msg as OSError: Bad message. could someone help me out thanks in advance.

import os
from six import BytesIO
import base64
myUsername = "a123"
myPassword = "124qwe"
myHostname = "abc.com"
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
with pysftp.Connection(host=myHostname, username=myUsername,password=myPassword,cnopts=cnopts) as sftp:
    print ("Connection succesfully stablished ... ")
    remoteFilePath = r"\GLOBAL\test\c1a0604437be43598a0dfe7ddef5b992_1"
    #path = os.path.join(remoteFilePath,folder_name,tray_number,file_name +'.pdf')
    sftp.chdir(remoteFilePath)
    filename=[]
    for f in sorted(sftp.listdir_attr(), key=lambda k: k.st_mtime, reverse=True):
        filename.append(f.filename)
    path = os.path.join(remoteFilePath,filename[0])
    try:
        print(sftp.stat(path)) #Throws an filenot error if the doesnt exists
        flo = BytesIO()
        sftp.getfo(path, flo)
        flo.seek(0)
        encoded_img_data = base64.b64encode(flo.getvalue())
        img_data=encoded_img_data.decode('utf-8')
        print("done")
    except FileNotFoundError:
        sftp.close()
        print("not done")

0 Answers0