Skip to content

Instantly share code, notes, and snippets.

@codeslinger
Forked from ovidiucs/paramiko-proxy.py
Created December 30, 2019 16:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codeslinger/01ab8961fb72c74b6952997c42d6c753 to your computer and use it in GitHub Desktop.
Save codeslinger/01ab8961fb72c74b6952997c42d6c753 to your computer and use it in GitHub Desktop.
Paramiko Connect via proxy
#!/usr/bin/env python
#-*- coding:utf8 -*-
# sources
# 1. https://gist.github.com/tell-k/4943359#file-paramiko_proxycommand_sample-py-L11
# 2. https://github.com/paramiko/paramiko/pull/97
# info: http://bitprophet.org/blog/2012/11/05/gateway-solutions/
# local -> proxy-server -> dest-server
# ~/.ssh/config
#
# Host proxy-server
# User hoge
# HostName proxy.example.com
# IdentityFile ~/.ssh/id_rsa_proxy
#
# Host dest-server
# User fuga
# HostName proxy.example.com
# IdentityFile ~/.ssh/id_rsa_dest
# ProxyCommand ssh proxy-server nc %h %p
#
import os
import sys
import paramiko
def test_client(host_name):
conf = paramiko.SSHConfig()
conf.parse(open(os.path.expanduser('~/.ssh/config')))
host = conf.lookup(host_name)
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(
host['hostname'], username=host['user'],
# if you have a key file
# key_filename=host['identityfile'],
password='yourpassword',
sock=paramiko.ProxyCommand(host.get('proxycommand'))
)
stdin, stdout, stderr = client.exec_command('command to run on dest-host')
print stdout.read()
if __name__ == '__main__':
test_client(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment