Skip to content

Instantly share code, notes, and snippets.

@aidnurs
Created June 4, 2023 14:54
Show Gist options
  • Save aidnurs/5af64f975b090142607e9775b2331444 to your computer and use it in GitHub Desktop.
Save aidnurs/5af64f975b090142607e9775b2331444 to your computer and use it in GitHub Desktop.
Nested SSH using Python Paramiko
import paramiko
# SSH jump server details
jump_server_host = '<host>'
jump_server_username = '<user>'
jump_server_password = '<password>'
# SFTP server details
sftp_server_host = '<host>'
sftp_server_username = '<user>'
sftp_server_password = '<password>'
jump_ssh = paramiko.SSHClient()
jump_ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
jump_ssh.connect(jump_server_host, username=jump_server_username, password=jump_server_password)
transport = jump_ssh.get_transport()
dest_addr = (sftp_server_host, 22)
local_addr = ('localhost', 0)
channel = transport.open_channel("direct-tcpip", dest_addr, local_addr)
sftp = paramiko.SSHClient()
sftp.set_missing_host_key_policy(paramiko.AutoAddPolicy())
sftp.connect(sftp_server_host, username=sftp_server_username, password=sftp_server_password, sock=channel)
sftp_conn=sftp.get_transport().open_session()
sftp_client = sftp.open_sftp()
files = sftp_client.listdir('.')
for file in files:
print(file)
sftp.close()
jump_ssh.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment