Search code examples
pythonpopenssh-tunnel

How do I close an ssh Tunnel opened through Popen in python


I need to create an ssh tunnel, then do something, then tear the tunnel down.

I have been trying to do it like this:

def runCmd(self,cmd):
    args = shlex.split(cmd)
    return subprocess.Popen(args)

def openTunnel
    cmd = 'ssh -f -N -L 1313:localhost:1313 userid@server.com'
    self.TunnelObj = self.runCmd(cmd)

That creates my Tunnel. I can then do the stuff I need to do. Now I want to tear down the tunnel.

    def closeSocket(self):
        print '\nClosing Tunnel\n'
        if self.TunnelObj.returncode == None: 
            print '\nabout to kill\n'
            self.TunnelObj.kill()

But the tunnel is still open. An ssh session still exists, and the port is still assigned.

How can I shut this tunnel down?


Solution

  • Part of the problem is that the tunnel process is a subprocess of self.TunnelObj. You can try to omit the -f flag so you hold the tunnel process directly.

    Another option would be to look at the paramiko library and this question.