Search code examples
pythonsftp

file pull from SFTP using python


from msilib.schema import Directory
import pysftp
import os
import glob
import fnmatch
from datetime import date, timedelta
 
cnopts = pysftp.CnOpts()

cnopts.hostkeys = None

myHostname = 'sftp.mmm.com'
myUsername = 'uuuu'
myPassword = 'pass'

with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
    print("Connection Success")

remotefilepath='/REPORTING/test.zip'

localfilepath='Z:\\data\\sftp_data\\'

sftp.get(remotefilepath,localfilepath)

Hi All I have been using above code to pull the file from SFTP and save locally However i am getting below error

chan = t.open_session( AttributeError: 'NoneType' object has no attribute 'open_session'

Please advise


Solution

  • When the with statement ends, after the print, the connection is automatically closed. That's what with is for. Either change to a simple

    sftp = pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts)
    

    or indent the rest of the script so it's inside the with:

    with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
        print("Connection Success")
        remotefilepath='/REPORTING/test.zip'
        localfilepath='Z:\\data\\sftp_data\\'
        sftp.get(remotefilepath,localfilepath)