Created
July 31, 2020 10:11
-
-
Save thiagorb/c8120c1529e9fac443143694f396a7ff to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Simple TCP proxy server | |
# | |
# This script can be used to route traffic from one host to another. | |
# | |
# Example: | |
# proxy.py 127.0.0.1 8080 example.org 80 | |
# | |
# Running the command above will start a TCP server listening on 127.0.0.1:8080. | |
# When a client connects to it, it will start a connection to example.org:80, and | |
# proxy the data from the client to the target, and from the target back to the client. | |
import asyncio | |
import sys | |
script_path, local_address, local_port, remote_address, remote_port = sys.argv | |
async def proxy(reader, writer): | |
while True: | |
data = await reader.read(1024) | |
if not data: | |
break | |
writer.write(data) | |
await writer.drain() | |
writer.close() | |
async def handle_connection(source_reader, source_writer): | |
target_reader, target_writer = await asyncio.open_connection(remote_address, remote_port) | |
await asyncio.wait([proxy(source_reader, target_writer), proxy(target_reader, source_writer)]) | |
loop = asyncio.get_event_loop() | |
coro = asyncio.start_server(handle_connection, local_address, local_port, loop=loop) | |
server = loop.run_until_complete(coro) | |
try: | |
loop.run_forever() | |
except KeyboardInterrupt: | |
pass | |
server.close() | |
loop.run_until_complete(server.wait_closed()) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment