Bootstrap FreeKB - Python (Scripting) - SSH ProxyCommand using paramiko
Python (Scripting) - SSH ProxyCommand using paramiko

Updated:   |  Python (Scripting) articles

This assumes you are already familiar with making an SSH connect to a system using Python paramiko. If not, check out my article FreeKB - Python (Scripting) - SSH using paramiko.

Let's say you have two servers

  • server1.example.com
  • server2.example.com

And let's say john.doe is able to make an SSH connection to server1 but is not allowed to make an SSH connection to server2. Let's also say that jane.doe is allowed to make an SSH connection from server1 to server2. One option here would be to use ProxyCommand to make an SSH connection to server1 as john.doe and then to server2 as jane.doe.

#!/usr/bin/python
import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())

server1_hostname = "server1.example.com"
server1_user     = "john.doe"
server2_hostname = "server2.example.com"
server2_port     = 22
server2_user     = "jane.doe"
ssh_key          = f"/home/{server1_user}/.ssh/id_rsa"

proxy_sock = paramiko.ProxyCommand(f"ssh -W {server2_hostname}:{server2_port} {server1_user}@{server1_hostname}")


try:
  ssh.connect(server2_hostname, username=server2_user, key_filename=ssh_key, sock=proxy_sock)
except Exception as exception:
  print(f"exception = {exception}")
else:
  print(f"SSH connection successful")

try:
  ssh.close()
except Exception:
  pass

 

 

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter bb5bc9 in the box below so that we can be sure you are a human.