git @ Cat's Eye Technologies Dipple / master python / noocat
master

Tree @master (Download .tar.gz)

noocat @masterraw · history · blame

#!/usr/bin/env python

# This is a stripped-down version of
#   https://web.archive.org/web/20090105185703/http://4thmouse.com/wp-content/uploads/2008/02/net_tool.py
# The closest to a license I could find is this exchange in the comment
# section of this blog post:
#   https://web.archive.org/web/20090105185703/http://4thmouse.com/index.php/2008/02/20/netcat-clone-in-three-languages-part-i-ruby/
# "Can i re-use your code here with some modifications?"
# "Please do. All examples on the site are fair game."

# SPDX-FileCopyrightText: 2008 Michael Smit
# SPDX-FileCopyrightText: 2011 Chris Pressey
#
# SPDX-License-Identifier: LicenseRef-4thmouse-fair-game

import sys
import socket
import select
import subprocess

def communicate(s, stdin, stdout):
	s.setblocking(0)
	while True:
		read_ready, write_ready, in_error = select.select([s, stdin], [], [s, stdin])
		try:
			buffer = s.recv(100)
			while buffer  != '':
				stdout.write(buffer)
				stdout.flush()
				buffer = s.recv(100)
			if buffer == '':
				return
		except socket.error:
			pass
		while True:
			r, w, e = select.select([stdin], [], [], 0)
			if len(r) == 0:
				break
			c = stdin.read(1)
			if c == '':
				return
			if s.sendall(c) != None:
				return

host = sys.argv[1]
port = int(sys.argv[2])
cmd = sys.argv[3]

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect( (host, port) )

p = subprocess.Popen(cmd, shell=True, bufsize=0, stdin=subprocess.PIPE, stdout=subprocess.PIPE)

communicate(s, p.stdout, p.stdin)