views:

181

answers:

1

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.

Any help would be greatly appreciated...

+2  A: 

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.

Alex Martelli
Beautiful! The thread module along with making the ForwardServer available did the trick.
PlaidFan