Skip to content

Instantly share code, notes, and snippets.

@tintoy
Created April 27, 2018 02:45
Show Gist options
  • Save tintoy/443c42ea3865680cd624039c4bb46219 to your computer and use it in GitHub Desktop.
Save tintoy/443c42ea3865680cd624039c4bb46219 to your computer and use it in GitHub Desktop.
SSH via jump-hosts using Paramiko
#!/usr/bin/env python3
import os
import paramiko
ssh_key_filename = os.getenv('HOME') + '/.ssh/id_rsa'
jumpbox_public_addr = '168.128.52.199'
jumpbox_private_addr = '10.0.5.10'
target_addr = '10.0.5.20'
jumpbox=paramiko.SSHClient()
jumpbox.set_missing_host_key_policy(paramiko.AutoAddPolicy())
jumpbox.connect(jumpbox_public_addr, username='root', key_filename=ssh_key_filename)
jumpbox_transport = jumpbox.get_transport()
src_addr = (jumpbox_private_addr, 22)
dest_addr = (target_addr, 22)
jumpbox_channel = jumpbox_transport.open_channel("direct-tcpip", dest_addr, src_addr)
target=paramiko.SSHClient()
target.set_missing_host_key_policy(paramiko.AutoAddPolicy())
target.connect(target_addr, username='root', key_filename=ssh_key_filename, sock=jumpbox_channel)
stdin, stdout, stderr = target.exec_command("ifconfig")
for line in stdout.read().split(b'\n'):
print(str(line))
target.close()
jumpbox.close()
@nlduarte
Copy link

When I tried to run multiple commands, the ssh session close at the second command:

I only add this code:

   command_list = ["show ver", "show run"]
    for command in command_list:
        stdin, stdout, stderr = target.exec_command(command)
       
        for line in stdout.read().split(b'\n'):
            print(str(line))

I got the error:
raise SSHException("SSH session not active")
paramiko.ssh_exception.SSHException: SSH session not active

Any ideas guys?

I am trying jumpssh library:
https://pypi.org/project/jumpssh/

Thank you for your response : )

@dan-gut1
Copy link

dan-gut1 commented Oct 6, 2024

Hey man, just wanted to say thanks for this piece of Code! truly helped me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment