Skip to content

Instantly share code, notes, and snippets.

@Bluehorn
Created August 31, 2012 21:26
Show Gist options
  • Save Bluehorn/3559286 to your computer and use it in GitHub Desktop.
Save Bluehorn/3559286 to your computer and use it in GitHub Desktop.
Snippet to tunnel an HTTP connection via paramiko (using urllib3)
import urllib3
import paramiko
from pprint import pprint
from httplib import HTTPConnection
import logging
logging.basicConfig(level=logging.DEBUG)
class TunnelingPoolManager(urllib3.PoolManager):
def __init__(self, ssh_client=None, **kwargs):
super(TunnelingPoolManager, self).__init__(**kwargs)
self._ssh_client = ssh_client
def _new_pool(self, scheme, host, port):
if scheme == "http":
return TunnelHTTPConnectionPool(host, ssh_client=self._ssh_client, port=port)
else:
return super(TunnelingPoolManager, self)._new_pool(scheme, host, port)
class TunnelHTTPConnectionPool(urllib3.HTTPConnectionPool):
def __init__(self, host, ssh_client=None, **kwargs):
super(TunnelHTTPConnectionPool, self).__init__(host, **kwargs)
self._ssh_client = ssh_client
def _new_conn(self):
def monkey_connect():
self = conn
self.sock = ssh_client.get_transport().open_channel(
"direct-tcpip", (self.host, self.port), ("client", 7337))
conn = HTTPConnection(host=self.host, port=self.port)
conn.connect = monkey_connect
return conn
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect('INTERNET_GATEWAY.my_site.net')
http = TunnelingPoolManager(ssh_client=ssh_client)
for x in range(2):
r = http.request('GET', 'http://jenkins/')
print r.status
pprint(r.headers)
print r.data
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment