Sabbir
Sabbir

Reputation: 1374

Execute Git Command with SSH agent using python pramiko

I've a server hosted on AWS EC2. Basically I update server version using pure git command from bitbucket.

Using Something like:

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

this is a pretty manual process. So, I want to do that using Python + Paramiko library.

But its not working actually.

N.B: I logged on to that server using paramiko + ssh key

How can I use python + paramiko to update from git repo?

Upvotes: 2

Views: 1382

Answers (1)

spirit
spirit

Reputation: 21

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

This works for me.

Upvotes: 2

Related Questions