可乐博客

Python简单实现端口转发

#tcp server
import socket
from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(2)

f_host, f_port = '127.0.0.1', 6001          #Local Server IP
t_host, t_port = '127.0.0.1', 80       #Real Server IP

pack_size = 20480
nat_type = ['ssh', 'http'][1]

def nat_ssh(ss, cl):
    while 1:
        msg = ss.recv(pack_size)
        cl.send(msg)
        print("Get:"+repr(msg))

def nat_http(ss, cl):
    while 1:
        msg = ss.recv(pack_size)
        cl.send(msg)
        print("Get:"+repr(msg))
        buf = cl.recv(pack_size)
        ss.send(buf)
        print("Get:"+repr(buf))

def get_ss_cl(f_host, f_port, t_host, t_port):
    server = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    server.bind((f_host,f_port))
    server.listen(20)
    ss, addr = server.accept()

    cl = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    cl.connect((t_host,t_port))
    return ss, cl

if __name__ == '__main__':
    print("Map Server start from {}:{} to {}:{}\r\n".format(f_host, f_port, t_host, t_port))
    ss, cl = get_ss_cl(f_host, f_port, t_host, t_port)
    if nat_type == 'ssh':
        executor.submit(nat_ssh, ss, cl)
        executor.submit(nat_ssh, cl, ss)    
    if nat_type == 'http':
        executor.submit(nat_http, ss, cl)
随笔