Skip to main content
 首页 » 编程设计

python之使用 python pramiko 通过 SSH 代理执行 Git 命令

2024年10月25日7jackei

我有一个托管在 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 key

登录到该服务器

如何使用 python + paramiko 从 git repo 更新?

请您参考如下方法:

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)) 

这对我有用。