之前遇到一個場景是這樣的:
我在自己的電腦上需要用mongodb圖形客戶端,但是mongodb的服務器地址沒有對外網開放,只能通過先登錄主機A,然后再從A連接mongodb服務器B。
本來想通過ssh端口轉發的,但是我沒有從機器A連接ssh到B的權限。于是就自己用python寫一個。
?
原理很簡單。
1.開一個socket server監聽連接請求
2.每接受一個客戶端的連接請求,就往要轉發的地址建一條連接請求。即client->proxy->forward。proxy既是socket服務端(監聽client),也是socket客戶端(往forward請求)。
3.把client->proxy和proxy->forward這2條socket用字典給綁定起來。
4.通過這個映射的字典把send/recv到的數據原封不動的傳遞
?
          下面上代碼。
          
           ?
          
        
            
#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(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()#代理服務器監聽的地址 
  except KeyboardInterrupt: 
    sys.exit(1)
          
        
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
 
					微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
 
					

