Before encountering a scenario is this:
I need to use MongoDB graphics client on my own computer, but MongoDB's server address is not open to external network, only can be connected to Mongodbserverb by logging on to host a first.
I wanted to forward it through Sshport, but I didn't have permission to connect SSH to B from machine A. So I wrote one in Python.
The principle is very easy.
1. Open a socket server to listen for connection requests
2. For each client connection request, a connection request is created for the address to be forwarded. That is Client->proxy->forward. Proxy is both the socket Server (listener client). Also the socket client (toward forward request).
3. Bind the 2 sockets of Client->proxy and Proxy->forward in a dictionary.
4. Pass the SEND/RECV data intact through this mapped dictionary
The code below.
#coding =utf-8import socketimport Selectimport systo_addr = (' xxx.xxx.xx.xxx ', 10000) #转发的地址class proxy:def __init__ (sel F, addr): Self.proxy = Socket.socket (socket.af_inet,socket. SOCK_STREAM) self.proxy.bind (addr) Self.proxy.listen (Ten) self.inputs = [Self.proxy] Self.route = {} def serve_forever (self): print ' proxy listen ... ' While 1:readable, _, _ = Select.select (Self.inputs, [], []) for self.sock in readable:if Self.sock = = Self.proxy: Self.on_join () Else:data = SELF.SOCK.RECV (8096) if not data: Self.on_quit () else:self.route[self.sock].send (data) def On_ Join (self): client, addr = Self.proxy.accept () print addr, ' connect ' forward = socket.socket (socket. Af_inet, Socket. SOCK_STREAM) Forward.connect (to_addr) self.inputs + = [Client, forward] self.route[client] = forward Self.route[forward] = client def on_quit (self): fo R S in Self.sock, Self.route[self.sock]: Self.inputs.remove (s) del Self.route[s] S.close ( if __name__ = = ' __main__ ': Try:proxy ((', 12345). Serve_forever () #代理server监听的地址 except Keyboardinterrupt: Sys.exit (1)
Effects such as the following.
50 lines of Python code implements a proxy server (you know)