实现本地服务与远程服务映射代码
# -*- coding:utf-8 -*-
# @author:
# @file: conntect_tool.py
import socket
import threading
import sys
# 端口映射配置信息
CFG_REMOTE_IP = '远程服务IP'
CFG_REMOTE_PORT = '远程服务端口号'
CFG_LOCAL_IP = '0.0.0.0'
# 接收数据缓存大小
PKT_BUFF_SIZE = 2048
# 单向流数据传递
def tcp_mapping_worker(conn_receiver, conn_sender):
while True:
try:
data = conn_receiver.recv(PKT_BUFF_SIZE)
except Exception:
break
if not data:
break
try:
conn_sender.sendall(data)
except Exception:
break
conn_receiver.close()
conn_sender.close()
return
# 端口映射请求处理
def tcp_mapping_request(local_conn, remote_ip, remote_port):
remote_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
remote_conn.connect((remote_ip, remote_port))
except Exception:
local_conn.close()
return
threading.Thread(target=tcp_mapping_worker, args=(local_conn, remote_conn)).start()
threading.Thread(target=tcp_mapping_worker, args=(remote_conn, local_conn)).start()
return
# 端口映射函数
def tcp_mapping(remote_ip, remote_port, local_ip, local_port):
local_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
local_server.bind((local_ip, local_port))
local_server.listen(5)
while True:
try:
(local_conn, local_addr) = local_server.accept()
except KeyboardInterrupt:
local_server.close()
break
threading.Thread(target=tcp_mapping_request, args=(local_conn, remote_ip, remote_port)).start()
return
# 主函数
if __name__ == '__main__':
params = sys.argv
CFG_LOCAL_PORT = params[1]
tcp_mapping(CFG_REMOTE_IP, CFG_REMOTE_PORT, CFG_LOCAL_IP, int(CFG_LOCAL_PORT))
#执行命令: python XX.py 本地端口号