Skip to content

Instantly share code, notes, and snippets.

@ckhung
Last active Dec 3, 2021
Embed
What would you like to do?
multicast netcat
#!/usr/bin/python3
# multicast netcat
# https://newtoypia.blogspot.com/2021/09/netcat.html
# 齊步走! 用 netcat 同步指揮教室裡的所有電腦
import argparse, sys, re, readline
from warnings import warn
from subprocess import Popen, PIPE
parser = argparse.ArgumentParser(
description='multicast netcat',
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('-r', '--remotelist', type=str,
help='file containing the list of remote hosts')
parser.add_argument('-p', '--port', type=int,
help='default port for remote hosts whose ports are not specified')
args = parser.parse_args()
host_port = {}
with open(args.remotelist) as hostlist:
for line in hostlist.readlines():
if re.match(r'^\s*#', line): continue
m = re.match(r'^\s*(\S+)(\s+(\d+))?', line)
if m:
host_port[m.group(1)] = m.group(3) if m.group(3) else args.port
else:
warn('ignoring unrecongnized line\n' + line.rstrip())
print(host_port)
print('=' * 60)
proc_list = []
for host in host_port.keys():
cmd = ['nc', host, str(host_port[host])]
proc = Popen( cmd, stdin=PIPE, universal_newlines=True, bufsize=1 )
proc_list.append({
'host': host,
'port': host_port[host],
'proc': proc
})
while True:
line = input('mcnc> ') + '\n'
#for line in sys.stdin:
if re.match(r'^\s*exit\s*$', line): break
for p in proc_list:
try:
p['proc'].stdin.write(line)
except BrokenPipeError:
warn('failed writing to [' + p['host'] + ']')
for p in proc_list:
p['proc'].stdin.close()
p['proc'].wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment