我需要使用 paramiko 实现一个 ssh 服务器,它只处理像这样的“-R”端口转发请求:
ssh -N -T -R 40005:destination_host:22 user@example.com
到目前为止,据我了解,我必须实现 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 还是其他地方启动线程?