Python ssh 上传文件

一、安装

安装python

链接: python3详细安装教程

安装paramiko(模块)

pip install paramiko

二、代码

V1.0

#V1  2022-9-11 20:51
#CY	
import paramiko
import os

hostname = '服务端地址'
username = '服务端用户名'
password = '服务端密码'

tran = paramiko.Transport(hostname,22)
#连接SSH服务端
tran.connect(username=username,password=password)
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)

for root, dirs, files in os.walk(".", topdown=False):
    for name in files:
        # 修改root路径(文件的目录路径)
        root = root.replace(".\\","/")
        if(root == "."):
            root = root.replace(".","/")
        root = root.replace("\\","/")
        if(root != "/"):
            root = root + "/"


        #检查路径中的文件夹是否存在,不存在则创建
        try:
            remotepath="/our/Test" +root#上传对象保存的文件路径
            sftp.stat(remotepath)
        except Exception as e:
                sshclt = paramiko.SSHClient()
                sshclt.set_missing_host_key_policy(paramiko.AutoAddPolicy())
                sshclt.connect(hostname=hostname, port=22, username=username, password=password,
                            allow_agent=False, look_for_keys=False)
                sshclt.exec_command("mkdir -p %s"%remotepath)
                print("创建路径"+root)

        # 上传文件
        localpath = "." + root + name
        remotepath = "/our/Test" + root + name
        #执行上传动作
        sftp.put(localpath,remotepath)

        print("上传("+ name +")成功")
# 断开连接
tran.close()
print("所有文件上传成功")

V2.0 修改创建文件夹时存在多次连接

#V2  2022-9-12 16:16
#CY	
time_start =  time.perf_counter()

pathHome = "/our/Test/" #服务器存放文件地址
hostname = '服务端地址'
username = '服务端用户名'
password = '服务端密码'
tran = paramiko.Transport(hostname,22)

#连接SSH服务端
tran.connect(username=username,password=password)
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)

#创建文件夹时会使用到
sshclt = paramiko.SSHClient()
sshclt.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshclt.connect(hostname=hostname, port=22, username=username, password=password,
            allow_agent=False, look_for_keys=False)


for root, dirs, files in os.walk(".", topdown=False):
    
    # 修改root路径(文件的目录路径)
    root = root.replace(".\\","")
    if(root == "."):
        root = root.replace(".","")
    root = root.replace("\\","/")
    if(root != "/"):
        root = root + "/"

    for name in files:
        
        #检查路径中的文件夹是否存在,不存在则创建
        try:
            remotepath=pathHome +root#上传对象保存的文件路径
            
            sftp.stat(remotepath)
        except Exception as e:
                sshclt.exec_command("mkdir -p %s"%remotepath)
                # print("创建路径"+root)

        # 上传文件
        localpath = "./" + root + name
        remotepath = pathHome + root + name

        # sftp.put(localpath,remotepath)
        # print("上传("+ name +")成功")

time_end =  time.perf_counter()
print("任务完成,耗时"+str(time_end - time_start)+"s")

tran.close()

V3.0 取消git文件的上传

#V3  2022-9-14 23:46
#CY	
import paramiko
import os
import time


time_start =  time.perf_counter()

pathHome = "/our/Test/" #服务器存放文件地址
hostname = '服务端地址'
username = '服务端用户名'
password = '服务端密码'
tran = paramiko.Transport(hostname,22)

#连接SSH服务端
tran.connect(username=username,password=password)
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)

#创建文件夹时会使用到
sshclt = paramiko.SSHClient()
sshclt.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshclt.connect(hostname=hostname, port=22, username=username, password=password,
            allow_agent=False, look_for_keys=False)

git_num = 0
for root, dirs, files in os.walk(".", topdown=False):
    if ".git" in root:
        git_num = git_num + 1
        print("git文件取消上传,第",git_num,"个")
        continue
    # 修改root路径(文件的目录路径)
    root = root.replace(".\\","")
    if(root == "."):
        root = root.replace(".","")
    root = root.replace("\\","/")
    if(root != "/"):
        root = root + "/"

    for name in files:
        
        #检查路径中的文件夹是否存在,不存在则创建
        try:
            remotepath=pathHome +root#上传对象保存的文件路径
            sftp.stat(remotepath)
        except Exception as e:
                sshclt.exec_command("mkdir -p %s"%remotepath)
                print("创建路径"+root)
                
        # 上传文件
        localpath = "./" + root + name
        remotepath = pathHome + root + name
        sftp.put(localpath,remotepath)
        print("上传("+ name +")成功")

time_end =  time.perf_counter()
print("任务完成,耗时"+str(time_end - time_start)+"s")

tran.close()

V4.0 增加进度条

import paramiko
import time
import os
import threading

def progressBar():
    global sc_size,sc_name
    size_all = 0
    for root, dirs, files in os.walk(".", topdown=False):
        if ".git" in root:
            continue
        for name in files:
            localpath =  root+ "\\" + name
            localpath = localpath.replace("\\","/")
            size  =  os.path.getsize(localpath)
            size_all = size + size_all
    start = time.perf_counter()
    print(("*"* 55)  + "任务开始" + ("*"* 55))
    while True:
        progress = (sc_size / size_all) * 100
        finsh = "▓" * int(progress)
        need_do = "-" * (100 - int(progress))
        dur = time.perf_counter() - start
        
        file_name = str(sc_name)
        if len(file_name) > 20:
            file_name = file_name[0:17]
            file_name = file_name + "···"
        else:
            while len(file_name)!=20:
                file_name=file_name + " "
            
        print("\r{:^3.0f}%[{}->{}]{:.2f}s(共 {} B,完成 {} B){}".format(progress, finsh, need_do, dur,size_all,sc_size-1,file_name), end="")
        if(progress >= 100):
            print("\n"+("*"* 55)  + "任务完成" + ("*"* 55))
            break


global sc_size,sc_name
sc_size = 1
sc_name = ""
threading.Thread(target=progressBar).start()

time_start =  time.perf_counter()
pathHome = "/our/Test/" #服务器存放文件地址
hostname = '服务端地址'
username = '服务端用户名'
password = '服务端密码'
tran = paramiko.Transport(hostname,22)

#连接SSH服务端
tran.connect(username=username,password=password)
#获取SFTP实例
sftp = paramiko.SFTPClient.from_transport(tran)

#创建文件夹时会使用到
sshclt = paramiko.SSHClient()
sshclt.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sshclt.connect(hostname=hostname, port=22, username=username, password=password,
            allow_agent=False, look_for_keys=False)

git_num = 0
file_num = 0


for root, dirs, files in os.walk(".", topdown=False):
    if ".git" in root:
        git_num = git_num + 1
        # print("git文件取消上传,第",git_num,"个")
        continue

    for name in files:
        #检查路径中的文件夹是否存在,不存在则创建
        try:
            remotepath=pathHome +root#上传对象保存的文件路径
            remotepath = remotepath.replace(".\\","")
            remotepath = remotepath.replace("/.","/")
            remotepath = remotepath.replace("\\","/")
            sftp.stat(remotepath)
        except Exception as e:
                sshclt.exec_command("mkdir -p %s"%remotepath)
                # print("创建路径"+root)
                
        # 上传文件
        localpath =  root+"/" + name
        localpath = localpath.replace("\\","/")
        remotepath = remotepath + "/" + name
        
        sftp.put(localpath,remotepath)
        size  =  os.path.getsize(localpath)
        sc_size = sc_size+size
        sc_name = name

time_end =  time.perf_counter()

tran.close()
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

超级小的大杯柠檬水

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值