title: Paramiko: Port Forwarding Around A NAT Router
body: <h2>Configuration</h2>
  <ul>
  <li><strong>LOCAL:</strong> A local machine that will create an ssh connection and issue commands on a REMOTE box.</li>
  <li><strong>PROXY:</strong> An EC-2 instance with ssh access to both LOCAL and REMOTE.</li>
  <li><strong>REMOTE:</strong> A remote machine sitting behind a NAT Router (inaccessible by LOCAL, but will open a connection to PROXY and allow LOCAL to tunnel to it).</li>
  </ul>
  <h2>Port Forwarding Steps (via command line)</h2>
  <ol>
  <li><p>Create an ssh connection from REMOTE to PROXY to forward ssh traffic on port 22 on the REMOTE machine to port 8000 on the PROXY server.</p>
  <blockquote>
  <p># Run from the REMOTE machine<br />
  ssh -N -R 0.0.0.0:8000:localhost:22 PROXY_USER@PROXY_HOSTNAME</p>
  </blockquote>
  </li>
  <li><p>Create an ssh tunnel from LOCAL to PROXY and forward ssh traffic from LOCAL:1234 to PROXY:8000 (which then forwards to REMOTE:22).</p>
  <blockquote>
  <p># Run from LOCAL machine<br />
  ssh -L 1234:localhost:8000 PROXY_USER@PROXY_HOSTNAME</p>
  </blockquote>
  </li>
  <li><p>Create the forwarded ssh connection from LOCAL to REMOTE (via PROXY).</p>
  <blockquote>
  <p># Run from LOCAL machine in a new terminal window<br />
  ssh -p 1234 REMOTE_USER@localhost</p>
  <p># I have now ssh'd to the REMOTE box and can run commands</p>
  </blockquote>
  </li>
  </ol>
  <h2>Paramiko Research</h2>
  <p>I have looked at a <a href="https://stackoverflow.com/questions/5852481/paramiko-ssh-port-forwarding-to-get-sql-dump">handful</a> of <a href="https://stackoverflow.com/questions/11294919/port-forwarding-with-paramiko">questions</a> related to port forwarding using Paramiko, but they don't seem to address this specific situation.</p>
  <h2>My Question</h2>
  <p>How can I use Paramiko to run steps 2 and 3 above? I essentially would like to run:</p>
  <pre><code>import paramiko
  
  # Create the tunnel connection
  tunnel_cli = paramiko.SSHClient()
  tunnel_cli.connect(PROXY_HOSTNAME, PROXY_PORT, PROXY_USER)
  
  # Create the forwarded connection and issue commands from LOCAL on the REMOTE box
  fwd_cli = paramiko.SSHClient()
  fwd_cli.connect('localhost', LOCAL_PORT, REMOTE_USER)
  fwd_cli.exec_command('pwd')
  </code></pre>