悉野小楼

导航

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 2024-08-20 16:41  悉野  阅读(9)  评论(0编辑  收藏  举报