Last active
September 12, 2017 22:36
-
-
Save cognifloyd/42198f1d4eaecc889309f2009187fed5 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
from __future__ import print_function | |
import eventlet | |
eventlet.monkey_patch() | |
import argparse | |
from nclib import TCPServer, Netcat, NetcatError, NetcatTimeout | |
def binds_arg(arg): | |
""" | |
:param str arg: | |
:return: | |
""" | |
parts = arg.split(':') | |
lparts = len(parts) | |
if lparts < 2 or lparts > 4: | |
raise argparse.ArgumentError(arg, 'Invalid ports argument') | |
dest_port = int(parts[-1]) | |
if lparts in [2, 3]: | |
src_ip = '0.0.0.0' | |
src_port = int(parts[0]) | |
else: # lparts == 4 | |
src_ip = parts[0] | |
src_port = int(parts[1]) | |
if lparts > 2: | |
dest_ip = parts[-2] | |
else: # lparts == 2 | |
dest_ip = '127.0.0.1' | |
return (src_ip, src_port), (dest_ip, dest_port) | |
def nc2nc(client1, client2): | |
""" | |
:param Netcat client1: | |
:param Netcat client2: | |
""" | |
while True: | |
try: | |
client1.send(client2.recv()) | |
except (NetcatError, NetcatTimeout) as e: | |
print(str(e) + ' %s:%d' % client1.peer) | |
client1.close() | |
client2.close() | |
return | |
def main(): | |
parser = argparse.ArgumentParser(description="Multi-client forwarding of TCP connections to a UDP port") | |
parser.add_argument( | |
'binds', | |
type=binds_arg, | |
help='from:to => TCP-PORT:UDP-PORT or [IP:]TCP-PORT:IP:UDP-PORT; default IPs: src 0.0.0.0, dest 127.0.0.1' | |
) | |
args = parser.parse_args() | |
src, dest = args.binds | |
print('%s => %s' % (src, dest)) | |
pool = eventlet.GreenPool() | |
tcp_server = TCPServer(src) | |
try: | |
for tcp_client in tcp_server: | |
print('Accepted client %s:%d' % tcp_client.peer) | |
udp_client = Netcat(dest, udp=True) | |
pool.spawn_n(nc2nc, tcp_client, udp_client) | |
pool.spawn_n(nc2nc, udp_client, tcp_client) | |
except KeyboardInterrupt: | |
tcp_server.close() | |
exit(0) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment