title: Is there a way to remotely port forward in Python 3? Ex: ssh jumpserver -L 8000:internal_server_name:8000 -N
body: <p>I have a manual process of port forwarding using OS based SSH forwarding currently and I would like to do this through Python so that the connection auto closes after. Similar to how a 'with open' would work for a file write.</p>
  <p>I am currently using it like so:
  ssh jumpserver -L 8000:internal_server_name:8000 -N</p>
  <p>and calling the api locally like so:
  http://localhost:8000/get-answer/</p>
  <p>This method works, but again, I am looking for a using/with open method.</p>
  <p>I tried this without luck:</p>
  <pre><code>remote_host = &quot;internal_server_name&quot;
  remote_port = 8000
  local_port  = 8000
  ssh_host    = &quot;jumpserver&quot;
  ssh_port    = 22
  
  user     = &quot;ubuntu&quot;
  pkey = &quot;~/.ssh.id_rsa&quot;
  
  transport = paramiko.Transport((ssh_host, ssh_port))
  
  # Command for paramiko-1.7.7.1
  transport.connect(hostkey  = None,
                  username = user,
                  password = None,
                  pkey     = pkey)
  
  try:
      forward_tunnel(local_port, remote_host, remote_port, transport)
  except KeyboardInterrupt:
      print ('Port forwarding stopped.')
      sys.exit(0)
  </code></pre>