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() paramiko.agent.AgentRequestHandler(s)
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 client.call it "t" session = t.get_session() paramiko.agent.AgentRequestHandler(s) # < -- - UNDOCUMENTED # do whatever you want with your session
# Author: toejough
# Website: https://github.com/toejough
'''
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__)
p.add_argument(
'host',
help='The host to connect to',
metavar='<hostname>'
)
p.add_argument(
'port',
help='The port to connect to',
metavar='<port>',
type=int
)
p.add_argument(
'username',
help='The username to connect as',
metavar='<username>'
)
p.add_argument(
'--debug',
help='Print verbose messages and full stack traces on internal failures',
action='store_true'
)
args = p.parse_args()
host, port, username = args.host, args.port, args.username
# Connection Attempt
try:
# Start the client
client = paramiko.client.SSHClient()
client.set_missing_host_key_policy(paramiko.client.AutoAddPolicy())
client.load_system_host_keys()
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")
time.sleep(0.1)
recv()
time.sleep(0.1)
recv()
# Play.
import pdb; pdb.set_trace() # XXX BREAKPOINT
exit(0)
eval `ssh-agent`
ssh - add~/.ssh/id_rsa
python agent.py
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/threading.py", line 810, in __bootstrap_inner
self.run()
File "/usr/lib/python2.7/dist-packages/paramiko/agent.py", line 116, in run
self._communicate()
File "/usr/lib/python2.7/dist-packages/paramiko/agent.py", line 128, in _communicate
events = select([self._agent._conn, self.__inr], [], [], 0.5)
TypeError: argument must be an int, or have a fileno() method.
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 AgentRequestHandler(session) # Commands executed after this point will see the forwarded agent on # the remote end. session.exec_command("git clone https://my.git.repository/")
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 main.py 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
user @example.com
$ ssh user @example.com $ cd~/.ssh $ ls
-- -- - BEGIN RSA PRIVATE KEY-- -- - ... -- -- - END RSA PRIVATE KEY-- -- -
$ pip3 install paramiko scp