title: python subprocess.Popen and ssh port forwarding in the background
body: <p>I need to have functionality that would essentially emulate user creating a port forwrding with ssh. So, essentially that should work like that:
   - execute <code>ssh -f -N -L 10000:gateway:11000 localhost</code>
   - if there is an output from that command, show to the user and pump user's input as a response
   - finish
  The code I came up with below, almost does what I need:</p>
  
  <pre><code>    ssh_proc = Popen(['ssh', '-f', '-N', '-L', '10000:gateway:11000', 'localhost'], stdin=PIPE, stdout=PIPE)
  stdoutdata, stderrdata = ssh_proc.communicate()
  </code></pre>
  
  <p>But the problem is it never finishes. I see the command is executed and forwarding tunnel is created but communicate() is still stuck. I can break out of that with Ctrl+C and get this:</p>
  
  <pre><code>    ^CTraceback (most recent call last):
    File "sshman.py", line 278, in &lt;module&gt;
      add(args.remote_host, args.remote_port, args.local_port, args.local_host)
    File "sshman.py", line 125, in add
      stdoutdata, stderrdata = ssh_proc.communicate()
    File "/usr/lib64/python2.7/subprocess.py", line 740, in communicate
      return self._communicate(input)
    File "/usr/lib64/python2.7/subprocess.py", line 1256, in _communicate
      stdout, stderr = self._communicate_with_poll(input)
    File "/usr/lib64/python2.7/subprocess.py", line 1310, in _communicate_with_poll
      ready = poller.poll()
  KeyboardInterrupt
  </code></pre>
  
  <p>Since i use -f with ssh command, it should fork the connection. Is there a way to interrupt communicate() when it is done or is there more elegant solution?</p>
  
  <p>Thank you in advance for any advices/suggestions/comments.</p>