linux端到linux端通過SFTP上傳下載檔案
阿新 • • 發佈:2021-02-07
環境和需求
1. 環境
1.linux客戶端A:192.168.50.112
1.linux-sftp服務端B:192.168.50.213
2. 需求
2.1 從A下載B伺服器上檔案
2.2從A上傳檔案到B伺服器上
程式碼實現
import paramiko, time from paramiko.ssh_exception import NoValidConnectionsError,AuthenticationException def sftp_get(ip, user, pwd, local_file,remote_file, port=22): try: t = paramiko.Transport(ip, port) t.connect(username=user, password=pwd) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(remote_file, local_file) t.close() except Exception as e: print(e) def sftp_put(ip, user, pwd, local_file, remote_file, port=22): try: t = paramiko.Transport(sock=(ip, port)) t.connect(username=user, password=pwd) sftp = paramiko.SFTPClient.from_transport(t) print(local_file) print(remote_file) sftp.put(local_file, remote_file) print(11) t.close() except Exception as e: print(e) if __name__ == '__main__': ''' 不要執行的,請註釋掉,前面加'#'符號 ''' ip = '192.168.50.213' user= 'mysftp' pwd= '12345678' local_file = '/angus/cc.txt' remote_file = '/upload/bb.txt' #sftp_get(ip=ip, user=user, pwd=pwd, remote_file=remote_file, local_file=local_file) sftp_put(ip=ip, user=user, pwd=pwd, local_file=local_file, remote_file=remote_file)
備註:remote_file使用的是sftp根目錄,並不是伺服器根目錄,否則會報檔案找不到