使用Python Paramiko通过SSH代理执行Git命令

2 投票
1 回答
1332 浏览
提问于 2025-04-18 16:58

我有一个在AWS EC2上托管的服务器。基本上,我是通过从Bitbucket上使用纯git命令来更新服务器版本。

我使用的命令大概是这样的:

ssh-agent /bin/bash
ssh-add .ssh/bitbucket_key
cd /var/www/my-git-bucket
git pull

这个过程比较手动,所以我想用Python + Paramiko库来实现自动化。

但是实际上它并没有成功。

注意:我是通过paramiko + ssh密钥登录到那个服务器的。

我该如何使用python + paramiko从git仓库更新呢?

1 个回答

2
def remote_exec(cmd_str, hostname, username, password, port, timeout=None):
    """
    execute command remotely
    :param cmd_str:
    :param hostname:
    :param username:
    :param password:
    :param port:
    :param timeout:
    :return:
    """

    try:
        max_size = 120 * 1024 * 1024
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(hostname=hostname, port=port, username=username, password=password, timeout=10)
        channel = client.get_transport().open_session()
        if timeout is None:
            timeout = 100
        channel.settimeout(timeout)
        channel.exec_command(cmd_str)
        content = ""
        data = channel.recv(1024)
        # Capturing data from channel buffer.
        while data:
            content += data
            data = channel.recv(1024)
        status, response, error = channel.recv_exit_status(), content, channel.recv_stderr(max_size)
        client.close()
        final_output = unicode(response) + unicode(error)
        return [status, final_output]
    except Exception, e:
        return [1, unicode(e)]
print(remote_exec("cd /var/www/my-git-bucket;git status", "127.0.0.1", "username", "password", 10022))

这个对我有效。

撰写回答