Question

I am trying to connect to a remote MySql server from my local machine. I want to run it whenever the DEBUG constant is set to true.

Here's the script:

import select
import SocketServer
import sys
import threading
import paramiko

SSH_PORT = 22
DEFAULT_PORT = 4000

g_verbose = True


class ForwardServer (SocketServer.ThreadingTCPServer):
    daemon_threads = True
    allow_reuse_address = True


class Handler (SocketServer.BaseRequestHandler):

    def handle(self):
        try:
            chan = self.ssh_transport.open_channel('direct-tcpip',
                                                   (self.chain_host, self.chain_port),
                                                   self.request.getpeername())
        except Exception, e:
            verbose('Incoming request to %s:%d failed: %s' % (self.chain_host,
                                                              self.chain_port,
                                                              repr(e)))
            return
        if chan is None:
            verbose('Incoming request to %s:%d was rejected by the SSH server.' %
                    (self.chain_host, self.chain_port))
            return

        verbose('Connected!  Tunnel open %r -> %r -> %r' % (self.request.getpeername(),
                                                            chan.getpeername(), (self.chain_host, self.chain_port)))
        while True:
            r, w, x = select.select([self.request, chan], [], [])
            if self.request in r:
                data = self.request.recv(1024)
                if len(data) == 0:
                    break
                chan.send(data)
            if chan in r:
                data = chan.recv(1024)
                if len(data) == 0:
                    break
                self.request.send(data)
        chan.close()
        self.request.close()
        verbose('Tunnel closed from %r' % (self.request.getpeername(),))


def forward_tunnel(local_port, remote_host, remote_port, transport):
    # this is a little convoluted, but lets me configure things for the Handler
    # object.  (SocketServer doesn't give Handlers any way to access the outer
    # server normally.)
    class SubHander (Handler):
        chain_host = remote_host
        chain_port = remote_port
        ssh_transport = transport
    ForwardServer(('', local_port), SubHander).serve_forever()


def verbose(s):
    if g_verbose:
        print s


HELP = """\
Set up a forward tunnel across an SSH server, using paramiko. A local port
(given with -p) is forwarded across an SSH session to an address:port from
the SSH server. This is similar to the openssh -L option.
"""

def forward():
    client = paramiko.SSHClient()
    client.load_system_host_keys()
    client.set_missing_host_key_policy(paramiko.WarningPolicy())

    try:
        print 'connecting'

        client.connect('*******', username='***', password='****!')

        print 'connected'
    except Exception, e:
        print '*** Failed to connect to %s:%d: %r' % ('*****', 22, e)
        sys.exit(1)

    try:
        forward_tunnel(3306, '127.0.0.1', 3306, client.get_transport())
    except SystemExit:
        print 'C-c: Port forwarding stopped.'
        sys.exit(0)

I have two problems here:
1) I don't know how and when to call my forward function when django raises.
2) When I access django locally and run the script from the console I get the following exception:

exception happened during processing of request from ('127.0.0.1', 41872) Traceback (most recent call last): File "/usr/lib/python2.6/SocketServer.py", line 558, in process_request_thread self.finish_request(request, client_address) File "/usr/lib/python2.6/SocketServer.py", line 320, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/lib/python2.6/SocketServer.py", line 615, in init self.handle() File "/home/omer/Aptana Studio 3 Workspace/Website/src/ssh_tunnel/tunnel.py", line 51, in handle verbose('Tunnel closed from %r' % (self.request.getpeername(),)) File "", line 1, in getpeername
File "/usr/lib/python2.6/socket.py", line 165, in _dummy raise error(EBADF, 'Bad file descriptor') error: [Errno 9] Bad file descriptor

Was this a bad idea to begin with?
Should I do this manually every time?

Was it helpful?

Solution

I don't think it's a bad idea.

I don't think you need to do it manually.

The exception is a bug in paramiko's forward code sample. This has been addressed by jhalcrow in the pull request here:

https://github.com/paramiko/paramiko/pull/36

This post has some code to do it in a more event driven way, i.e if you wanted to call it via some web event hooks in your django code or the like:

Paramiko SSH Tunnel Shutdown Issue

OTHER TIPS

humm, i didn't try this, but if you are on linux, could you run

ssh -L 3306:localhost:3306 remote.host.ip

through python system call when DEBUG is set?

also if you are on Windows, try putty with port forwarding

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top