One of the scenarios you've encountered before is this:
I need to use the MongoDB graphics client on my own computer, but the MongoDB server address is not open to the outside world, only by first logging in to host A and then connecting MongoDB Server B from a.
It was intended to be forwarded over the SSH port, but I did not have the right to connect SSH to B from machine A. So I wrote one for myself in Python.
The principle is simple.
1. Open a socket server to listen for connection requests
2. For each connection request that accepts a client, a connection request is built to the address to be forwarded. namely Client->proxy->forward. Proxy is both the socket Server (listener client) and the socket client (to forward request).
3. Bind the Client->proxy and Proxy->forward to the 2 sockets in a dictionary.
4. Through this mapping of the dictionary to Send/recv to the data passed unchanged
The code below.
#coding =utf-8 Import Socket Import Select Import sys to_addr = (' xxx.xxx.xx.xxx ', 10000) #转发的地址 class Proxy: def __init__ (self, addr): Self.proxy = Socket.socket (socket.af_inet,socket.
SOCK_STREAM) self.proxy.bind (addr) Self.proxy.listen 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:se
Lf.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 SE Lf.route[forwARD] = client def on_quit (self): for 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 () #代理服务器监听的
Address except KeyboardInterrupt:sys.exit (1)