以编程方式关闭 Paramiko 中的 SSH 隧道 [英] Shutting Down SSH Tunnel in Paramiko Programmatically
问题描述
我们正在尝试使用 paramiko 模块按需创建到任意服务器的 SSH 隧道,以查询远程数据库.我们尝试使用 paramiko 附带的 forward.py 演示,但最大的限制是似乎没有一种简单的方法可以在套接字服务器启动后关闭 SSH 隧道和 SSH 连接.
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.
我们的限制是我们无法从 shell 激活它,然后手动终止 shell 以停止侦听器.我们需要打开SSH连接,隧道,通过隧道执行一些操作,关闭隧道,在python中关闭SSH连接.
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.
我看到过对 server.shutdown() 方法的引用,但不清楚如何正确实现它.
I've seen references to a server.shutdown() method but it isn't clear how to implement it correctly.
推荐答案
我不知道你说的正确实现"是什么意思——你只需要跟踪服务器对象并调用 shutdown
就可以了.在forward.py
中,服务器没有被跟踪,因为forward_tunnel
的最后一行是
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()
并在单独的线程中运行 forward_tunnel
函数,以便 main
函数重新获得控制权(而 serve_forever
正在运行单独的线程)并且可以在适当和需要的时候调用 theserver.shutdown()
.
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.
这篇关于以编程方式关闭 Paramiko 中的 SSH 隧道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!