2012-11-27 24 views
5

我需要使用的paramiko只處理類似這樣的「-R」端口轉發請求到實施SSH服務器:的paramiko服務器模式端口轉發

ssh -N -T -R 40005:destination_host:22 [email protected] 

所以,從我瞭解我將不得不實施ServerInterface遠.check_port_forward_request,然後在某個時間點創建一個套接字並偵聽指定的端口。通過Channel/Connection進入的任何數據分別轉到Connection/Channel

class Server (paramiko.ServerInterface): 
    . 
    . 
    . 
    def check_port_forward_request(self, address, port): 
     'Check if the requested port forward is allowed' 
     ... 
     return port 

def handler(chan, port): 
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
    sock.bind(('', port)) 
    sock.listen(1) 
    conn, addr = s.accept()  

    while True: 
     r, w, x = select.select([conn, chan], [], []) 
     if conn in r: 
      data = conn.recv(1024) 
      if len(data) == 0: 
       break 
      chan.send(data) 
     if chan in r: 
      data = chan.recv(1024) 
      if len(data) == 0: 
       break 
      conn.send(data) 
    chan.close() 
    conn.close() 
    verbose('Tunnel closed from %r' % (chan.origin_addr,)) 

thr = threading.Thread(target=handler, args=(chan,server_port)) 
thr.setDaemon(True) 
thr.start() 

這是實現服務器端paramiko ssh端口轉發的一般思路嗎? 我應該在check_port_forward_request或其他地方啓動線程嗎?

回答