| 12
 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
 
 | import paramikoimport os
 
 hostname = 'xxx'
 username = 'xxx'
 password = 'xxx'
 port = 22
 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)
 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)
 else:
 continue
 
 if SFTP_DOWNLOAD_FLAG:
 SFTP_DOWNLOAD_FLAG = False
 sftp.remove(os.path.join(remote+f))
 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 __name__ == '__main__':
 
 sftp = sftpconnect(host, port, username, password)
 print(sftp)
 
 |