Skip to content

Instantly share code, notes, and snippets.

@golightlyb
Created July 7, 2016 18:25
Show Gist options
  • Save golightlyb/cc8606c5684334a50da37adb506d577f to your computer and use it in GitHub Desktop.
Save golightlyb/cc8606c5684334a50da37adb506d577f to your computer and use it in GitHub Desktop.
simple python3 wrapper to netcat (nc)
'''
nc.py - simple python3 wrapper to netcat (nc)
=============================================
Introducton
-----------
Netcat (http://nc110.sourceforge.net/) is a simple Unix utility which reads and
writes data across network connections. If you are running Linux, you probably
have a version of netcat installed already.
This file contains a simple wrapper to the netcat binary, /bin/nc, from python3
Usage
-----
`nc(host, port, input_byte_stream)`
* `host`: `str` indicating a hostname
* `port`: `int` port number
* `input_byte_stream`: any streamable bytes buffer,
such as `io.BytesIO(b'my string')`, or `sys.stdin.buffer`
Returns the output from nc as a streamable binary buffer.
Example
-------
import sys, io
raw_request = b"GET / HTTP/1.1\nHost: example.localhost\nConnection: close\n\n"
print(nc('example.localhost', 80, io.BytesIO(raw_request)).read())
print(nc('example.localhost', 80, sys.stdin.buffer).read())
Copying
-------
You are free to use this function as you please. Attribution is not required.
As a simple wrapper between two interfaces that have already been defined,
this function should not be considered a "creative work", and therefore is not
copyrightable. The "obviousness" of the function should additionally render it
nonpatentable. Further, I hereby choose to waive all moral rights to this work.
- Ben <ben@tawesoft.co.uk>
'''
def nc(host, port, input_byte_stream):
import subprocess
args=['/bin/nc', host, str(port)]
p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(input_byte_stream.read())
p.stdin.close()
return p.stdout
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment