开发者

Shutting Down SSH Tunnel in Paramiko Programmatically

We are attempting to use the paramiko module for creating SSH tunnels on demand to arbitrary servers for purposes of querying remote databases. We attempted to use the forward.py demo that ships with paramiko but the big limitation is there does not seem to be an easy way to close an SSH tunnel and the SSH connection once the socket server is started up.

The limitation we have is that we cannot activate this from a shell and then kill the shell manually to stop the listner. We need to open the SSH connection, tunnel, perform some ac开发者_Go百科tions through the tunnel, close the tunnel, and close the SSH connection within python.

I've seen references to a server.shutdown() method but it isn't clear how to implement it correctly.


I'm not sure what you mean by "implement it correctly" -- you just need to keep track of the server object and call shutdown on it when you want. In forward.py, the server isn't kept track of, because the last line of forward_tunnel is

ForwardServer(('', local_port), SubHander).serve_forever()

so the server object is not easily reachable any more. But you can just change that to, e.g.:

global theserver
theserver = ForwardServer(('', local_port), SubHander)
theserver.serve_forever()

and run the forward_tunnel function in a separate thread, so that the main function gets control back (while the serve_forever is running in said separate thread) and can call theserver.shutdown() whenever that's appropriate and needed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜