Before encountering a scenario like this:
I need a MongoDB graphics client on my computer, but MongoDB's server address is not open to the Internet, only by logging on to host A and then from a to MongoDB Server B.
I wanted to forward it through the SSH port, but I didn't have permission to connect SSH to B from machine A. So I wrote one in Python.
The principle is simple.
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 (listening client) and 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 () #代理服务器监听的地址 except Keyboardinterrupt: Sys.exit (1)
The effect is as follows.
50 lines of Python code to implement a proxy server (you know)