用paramiko做了一个自动化部署Python脚本

以下脚本解决了我本地编写调试完Python代码后,能快速部署至生产环境。不用再登录服务器,上传文件执行命令,等一堆的重复性工作。

import paramiko
# 设置SSH连接参数
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname='***.***.***.***', username='root', password='******')

# 设置源文件路径和目标路径
source_file = '/Users/penz/textin.py'
target_folder = '/opt/textin/textin.py'

# 使用SFTP传输文件
sftp = ssh.open_sftp()
sftp.put(source_file, target_folder)  # 目标文件名可以按需更改
sftp.close()

#这个地方我研究了很长时间,最好的方式就是把指令写在一起
stdin, stdout, stderr = ssh.exec_command(f'cd /opt/text_in/ && ./run && sleep 2 && cat run.log')

try:
    while True:
        # 读取一行输出
        line = stdout.readline()
        if line:
            print(line.strip())  # 直接打印读取到的行,不需要decode()
        else:
            # 如果读取到空行,可能是因为通道已经关闭
            break
except paramiko.SSHException as e:
    # 处理SSH异常,例如超时
    print("SSH exception occurred:", e)

# 获取错误输出
error_output = stderr.read().decode()  # 这里需要decode,因为stderr可能包含二进制数据
if error_output:
    print("Error output:")
    print(error_output)

stdout.close()
stderr.close()
# 关闭SSH连接
ssh.close()