Shutting Down SSH Tunnel in Paramiko Programmatically

徘徊边缘 提交于 2020-01-01 19:07:13

问题


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 actions 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.


回答1:


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.



来源:https://stackoverflow.com/questions/2777884/shutting-down-ssh-tunnel-in-paramiko-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!