Skip to content

Instantly share code, notes, and snippets.

@NicolaiSoeborg
Created November 15, 2024 14:22
Show Gist options
  • Save NicolaiSoeborg/be7a85a0adab5d0fb1ce3b64a919560d to your computer and use it in GitHub Desktop.
Save NicolaiSoeborg/be7a85a0adab5d0fb1ce3b64a919560d to your computer and use it in GitHub Desktop.
Forward many ports
import asyncio
TARGET_IP = '1.2.3.4'
async def print_lines(port, process):
while True:
line = await process.stdout.readline()
if not line:
print(f"[{port}]: Died?")
break
print(f"[{port}]: {line.decode().strip()}")
async def main():
procs = []
async with asyncio.TaskGroup() as tg:
try:
for port in [8080, 8081, 8082]:
cmd = f'socat -v TCP-LISTEN:{port},fork,reuseaddr TCP:{TARGET_IP}:{port}'
procs.append(await asyncio.create_subprocess_shell(
cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT
))
tg.create_task(print_lines(port, procs[-1]))
except KeyboardInterrupt:
print("Stopping")
for proc in procs:
proc.terminate()
if __name__ == '__main__':
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment