悉野小楼

导航

< 2025年3月 >
23 24 25 26 27 28 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 1 2 3 4 5

统计

python ssh上传文件到linux并解压

复制代码
import paramiko
import os

def upload_and_unzip(local_file, remote_file, zip_dir):
    # 创建SSH客户端
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    private_key_path = r'F:\mysite.pem'
    # 加载私钥文件
    private_key = paramiko.RSAKey.from_private_key_file(private_key_path)
    try:
        # 连接到远程服务器
        ssh.connect('111.111.111.111', username='root', pkey=private_key)

        # 创建zip目录
        ssh.exec_command(f'mkdir -p {zip_dir}')

        # 使用exec_command运行命令
        sftp = ssh.open_sftp()
        sftp.put(local_file, remote_file)
        sftp.close()

        # 解压文件
        stdin, stdout, stderr = ssh.exec_command(f'unzip -o {remote_file} -d {zip_dir}')
        stdout_lines = stdout.readlines()
        stderr_lines = stderr.readlines()

        # 输出解压过程的信息
        if stderr_lines:
            print("ERROR:")
            for line in stderr_lines:
                print(line.strip())
        else:
            print("文件上传并解压成功。")
            print("解压详情:")
            for line in stdout_lines:
                print(line.strip())

    except Exception as e:
        print(f"操作过程中出现错误: {e}")
    finally:
        # 断开连接
        ssh.close()
def listDir(folder):
    listFiles = os.listdir(folder)
    listRet = []
    for file in listFiles:
        fullPath = os.path.join(folder, file)
        if os.path.isfile(fullPath) and file.endswith('.zip'):
            listRet.append(fullPath)
    return listRet

if __name__ == "__main__":
    folder = r'E:\game-client\game\release'
    files = listDir(folder)
    # zip_dir_root = '/home/work/test_dir'
    zip_dir_root = '/home/work/client/game'

    for file in files:
        shortName = os.path.basename(file)
        zip_dir = zip_dir_root + '/game_' + os.path.splitext(shortName)[0]
        remote_file = zip_dir + "/web.zip"
        upload_and_unzip(file, remote_file, zip_dir)
    print("所有文件上传并解压完成。")
复制代码

upload_and_unzip.py

posted on   悉野  阅读(16)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2015-08-20 c#进制转换(转)
2014-08-20 wmware10安装ghost win7问题处理
点击右上角即可分享
微信分享提示