archive
/
tcp-nat-proxy
Archived
1
Fork 0
This repository has been archived on 2023-03-26. You can view files and clone it, but cannot push or open issues or pull requests.
tcp-nat-proxy/tcp_nat_proxy.py

65 lines
1.8 KiB
Python
Raw Normal View History

2019-01-01 19:07:00 +00:00
import argparse
2019-01-01 18:44:40 +00:00
import asyncio
2019-01-01 19:07:00 +00:00
from collections import namedtuple
2019-01-01 18:44:40 +00:00
2019-01-01 19:07:00 +00:00
Route = namedtuple("Route", ["listen_port", "destination_host", "destination_port"])
2019-01-01 18:44:40 +00:00
BUFFER_SIZE = 4096
2019-01-01 19:07:00 +00:00
def destination_host_display(route: Route):
return "{}:{}".format(route.destination_host, route.destination_port)
def parse_argument(value):
return Route(*value.split(":"))
2019-01-01 18:44:40 +00:00
async def pipe(reader, writer):
try:
while not reader.at_eof():
writer.write(await reader.read(BUFFER_SIZE))
finally:
writer.close()
2019-01-01 19:07:00 +00:00
async def create_proxy_pipe(route: Route):
2019-01-01 18:44:40 +00:00
async def handle_client(local_reader, local_writer):
try:
remote_reader, remote_writer = await asyncio.open_connection(
2019-01-01 19:07:00 +00:00
route.destination_host, route.destination_port
)
await asyncio.gather(
pipe(local_reader, remote_writer), pipe(remote_reader, local_writer)
2019-01-01 18:44:40 +00:00
)
2019-01-01 19:07:00 +00:00
except ConnectionRefusedError:
print("Connection to {} refused".format(destination_host_display(route)))
pass
2019-01-01 18:44:40 +00:00
finally:
local_writer.close()
2019-01-01 19:07:00 +00:00
server = await asyncio.start_server(handle_client, "0.0.0.0", route.listen_port)
print(
"Routing from {} to {}".format(
route.listen_port, destination_host_display(route)
)
)
2019-01-01 18:44:40 +00:00
await server.wait_closed()
async def main():
2019-01-01 19:07:00 +00:00
parser = argparse.ArgumentParser()
parser.add_argument(
"-R", "--route", action="append", required=True, type=parse_argument
)
args = parser.parse_args()
servers = [create_proxy_pipe(route) for route in args.route]
await asyncio.gather(*servers)
2019-01-01 18:44:40 +00:00
if __name__ == "__main__":
2019-01-01 19:07:00 +00:00
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Process terminated")