之前遇到一個(gè)場景是這樣的:
我在自己的電腦上需要用mongodb圖形客戶端,但是mongodb的服務(wù)器地址沒有對外網(wǎng)開放,只能通過先登錄主機(jī)A,然后再從A連接mongodb服務(wù)器B。
本來想通過ssh端口轉(zhuǎn)發(fā)的,但是我沒有從機(jī)器A連接ssh到B的權(quán)限。于是就自己用python寫一個(gè)。
原理很簡單。
1.開一個(gè)socket server監(jiān)聽連接請求
2.每接受一個(gè)客戶端的連接請求,就往要轉(zhuǎn)發(fā)的地址建一條連接請求。即client->proxy->forward。proxy既是socket服務(wù)端(監(jiān)聽client),也是socket客戶端(往forward請求)。
3.把client->proxy和proxy->forward這2條socket用字典給綁定起來。
4.通過這個(gè)映射的字典把send/recv到的數(shù)據(jù)原封不動的傳遞
下面上代碼。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
#coding=utf-8 import socket import select import sys to_addr = ( 'xxx.xxx.xx.xxx' , 10000 ) #轉(zhuǎn)發(fā)的地址 class Proxy: def __init__( self , addr): self .proxy = socket.socket(socket.AF_INET,socket.SOCK_STREAM) self .proxy.bind(addr) self .proxy.listen( 10 ) 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 ): 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() #代理服務(wù)器監(jiān)聽的地址 except KeyboardInterrupt: sys.exit( 1 ) |