#!/usr/bin/env python3 """Simple script that copies standard input to a listening socket. There is no protocol other then sending the stream block-by-block. If you want encryption, just encrypt the stream before sending. The following are examples of how to use this script: 1) Connect to remote host. Then, send file. send.py --host example.com --port 22789 < foo.gz 2) Listen for a new connection. Then, send file. send.py --listen --host 0.0.0.0 --port 22789 < foo.gz """ import argparse import socket import sys def main(): # Parse command-line arguments. parser = argparse.ArgumentParser( formatter_class=argparse.RawTextHelpFormatter, description="Copy standard input to a socket.", epilog="""Examples: 1) Connect to remote host then send file. send.py --host example.com --port 22789 < foo.gz 2) Listen for a new connection then send file. send.py --listen --host 0.0.0.0 --port 22789 < foo.gz """) parser.add_argument("--host", required=True, dest="host", help="host (default: None)") parser.add_argument("--listen", dest="listen", action="store_true", help="listen for connections (default: False)") parser.add_argument("--port", type=int, required=True, dest="port", help="port (default: None)") args = parser.parse_args() # Portably get standard I/O as a binary stream. if sys.version_info[0] >= 3: pstdin = sys.stdin.buffer pstdout = sys.stdout.buffer pstderr = sys.stderr.buffer else: pstdin = sys.stdin pstdout = sys.stdout pstderr = sys.stderr # Get a socket connection. if args.listen: # Listen for new socket connection. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) s.bind((args.host, args.port)) s.listen(1) c = s.accept()[0] else: # Create new socket connection. c = socket.socket(socket.AF_INET, socket.SOCK_STREAM) c.connect((args.host, args.port)) while True: # Read a block. buf = pstdin.read(16384) if not buf: break # Write a block. c.send(buf) if __name__ == "__main__": main()