开发者

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

开发者 https://www.devze.com 2023-03-12 00:28 出处:网络
I need to create an ssh tunnel, then do something, then tear the tunnel down. I have been trying to do it like this:

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):
    ar开发者_StackOverflowgs = 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消