ssh key-forwarding using python paramiko

  • Last Update :
  • Techknowledgy :

You can enable SSH agent forwarding for a session in paramiko using AgentRequestHandler. To do this, call paramiko.agent.AgentRequestHandler(s) with the session s. For example:

client = paramiko.client.SSHClient()
client.connect(host, port, username)
s = client.get_transport().open_session()

Suggestion : 2

A how-to for ssh-agent forwarding via Paramiko. Specifically, I used Paramiko v1.15.2 in this example.,Paramiko's docs do not document the API required to do ssh-agent forwarding. I ended up finding out how by reading pull requests for ssh-agent forwarding features in frameworks that use Paramiko under the covers, like fabric and ansible.,Besides attempting to document this process here, I've opened a bug with Paramiko to document this API in their official docs.,2、whether I can turn on the SSH agent forwarding use paramiko as the OpenSSH does

# get a paramiko transport - get it directly, or from a it "t"
session = t.get_session()
paramiko.agent.AgentRequestHandler(s) # < -- - UNDOCUMENTED
# do whatever you want with your session
# Author: toejough
# Website:

Tries to hop connections via 'Public-key' auth type and SSH agent.

# [ Imports ]
# [ - Python ]
from argparse import ArgumentParser
import sys
import time
# [ - Third Party ]
import paramiko

# [ Main ]
# Arg parsing
p = ArgumentParser(description=__doc__)
help='The host to connect to',
   help='The port to connect to',
      help='The username to connect as',
         help='Print verbose messages and full stack traces on internal failures',
         args = p.parse_args()
         host, port, username =, args.port, args.username
         # Connection Attempt
         # Start the client
         client = paramiko.client.SSHClient()
         client.connect(host, port, username)
         # get a session
         s = client.get_transport().open_session()
         # set up the agent request handler to handle agent requests from the server
         paramiko.agent.AgentRequestHandler(s) # <--UNDOCUMENTED??!! # get a shell s.get_pty() s.invoke_shell() except Exception as e: # if debugging, just re-raise the error so the full stacktrace is printed if args.debug: raise # On failure, print failure only (not full bt, as is the default without the try/catch) print e exit(1) def recv(): while s.recv_ready(): print s.recv(sys.maxint) while s.recv_stderr_ready(): print>> sys.stderr, s.recv_sterr(sys.maxint)

            def send(text):
            s.sendall(text + "\n")

            # Play.
            import pdb; pdb.set_trace() # XXX BREAKPOINT
eval `ssh-agent`
ssh - add~/.ssh/id_rsa

You might also want to point out that it's not useful to set up an AgentRequestHandler if there is no local agent, since in this case the connection will hang with a stack trace such as the one below as soon as a remote process tries to talk to the agent over the forwarded channel:

Exception in thread Thread - 82:
   Traceback(most recent call last):
   File "/usr/lib/python2.7/", line 810, in __bootstrap_inner
File "/usr/lib/python2.7/dist-packages/paramiko/", line 116, in run
File "/usr/lib/python2.7/dist-packages/paramiko/", line 128, in _communicate
events = select([self._agent._conn, self.__inr], [], [], 0.5)
TypeError: argument must be an int, or have a fileno() method.

Suggestion : 3

Client interface for using private keys from an SSH agent running on the local machine. If an SSH agent is running, this class can be used to connect to it and retrieve PKey objects which can be used when attempting to authenticate to remote SSH servers.,Upon initialization, a session with the local machine’s SSH agent is opened, if one is running. If no agent is running, initialization will succeed, but get_keys will return an empty tuple.,Return the list of keys available through the SSH agent, if any. If no SSH agent was running (or it couldn’t be contacted), an empty list will be returned.,Simply instantiate this class, handing it a live command-executing session object, and it will handle forwarding any local SSH agent processes it finds.

# Connect
client = SSHClient()
client.connect(host, port, username)
# Obtain session
session = client.get_transport().open_session()
# Forward local agent
# Commands executed after this point will see the forwarded agent on
# the remote end.
session.exec_command("git clone https://my.git.repository/")

Suggestion : 4

Automate remote server tasks by using the Paramiko & SCP Python libraries. Use Python to SSH into hosts, execute tasks, & transfer files.,SCP refers to both the protocol for copying files to remote machines (secure copy protocol) as well as the Python library, which utilizes this. We've already installed the SCP library, so import that shit. ,Check out how easy it is to create a that handles complex tasks on remote machines thanks to our RemoteClient class:,Remote Path: The path to the remote directory we're looking to target for file transfers. We can either upload things to this folder or download the contents of it.

$ ssh - keygen - t rsa
>> Generating a public / private rsa key pair. >>
   Enter the file in which you wish to save they key(i.e., /home/username / .ssh / id_rsa):
$ ssh - copy - id - i~/.ssh/mykey
$ ssh user
$ cd~/.ssh
$ ls
-- -- - BEGIN RSA PRIVATE KEY-- -- -


-- -- - END RSA PRIVATE KEY-- -- -
$ pip3 install paramiko scp