python通过sftp实现文件上传到Linux 服务器
python通过sftp实现文件上传到Linux 服务器

使用前安装工具包:  pip install paramiko

代码如下:

import sys
import time

import paramiko as pko

__server_host__ = ('IP', PORT)
__uname = 'root'
__passw = ''

def __result_handle(trans_length:int, total_length:int):
    percent_rate = str(round(trans_length/total_length, 4) * 100)
    print(f'\r...上传进度: {percent_rate}%', end="")

def send_file(local_filepath:str, remote_filepath:str) -> str:
    tp = pko.Transport(__server_host__)
    tp.connect(username=__uname, password=__passw)
    sftp = pko.SFTPClient.from_transport(tp)
    sftp.put(localpath=local_filepath,
    remotepath=remote_filepath,
             callback=__result_handle)
    tp.close()

if __name__ == '__main__':
    loc_file = input('本地文件路径:')
    rmt_file = input('远端文件路径:')
    if rmt_file is None or rmt_file == '':
        print('参数错误')
        sys.exit(-1)

    send_file(loc_file, rmt_file)
    time.sleep(1)
发布时间:2022-08-14 00:00:00 关键词:python sftp 浏览量:0