1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
|
Big Box Python the FTP SFTP AN class = "Line">
Import paramiko
Import os
= hostname 'XXX'
username = 'XXX'
password = 'XXX'
Port = 22 is
upload_local_dir = 'XXX'
download_local_dir = 'XXX'
remote_dir = 'Inbox /'
SFTP_DOWNLOAD_FLAG = False
def sftp_callback(transfered, total):
global SFTP_DOWNLOAD_FLAG
if transfered == total:
SFTP_DOWNLOAD_FLAG = True
def sftpconnect(host, port, username, password):
try:
sf = paramiko.Transport((host, port))
sf.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(sf)
return sftp
except Exception as e:
print('connect exception: ', e)
def sftp_upload(host, port, username, password, local, remote):
sf = paramiko.Transport((host, port))
sf.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(sf)
try:
if os.path.isdir(local):
for f in os.listdir(local):
sftp.put(os.path.join(local, f), os.path.join(remote+f))
else:
sftp.put(local, remote)
except Exception as e:
print('upload exception: ', e)
finally:
if sf is not None:
sf.close()
DEF sftp_download (Host, Port, username, password, local, Remote) :
Global SFTP_DOWNLOAD_FLAG SF = paramiko.Transport ((Host, Port)) sf.connect (username = username, password = password) SFTP paramiko.SFTPClient.from_transport = ( SF) the try :for f in SFTP. listdir (Remote): sftpAttributes = sftp.lstat (os.path.join (Remote + f)) fileSize = sftpAttributes.st_size IF fileSize:
sftp.get (os.path.join (Remote + f), os.path.join (local, f), sftp_callback)
the else : continue
IF SFTP_DOWNLOAD_FLAG:
SFTP_DOWNLOAD_FLAG = False
sftp.remove (os.path.join (Remote + f))
the else : os.remove (os .path.join (local, f))
except Exception as e:
print('download exception: ', e)
finally:
if sf is not None:
sf.close()
IF the __name__ == '__main__' :
SFTP = sftpconnect (Host, Port, username, password) Print (SFTP)
|