Skip to content

Instantly share code, notes, and snippets.

Last active July 30, 2023 16:28
Show Gist options
  • Star 70 You must be signed in to star a gist
  • Fork 22 You must be signed in to fork a gist
  • Save leonjza/f35a7252babdf77c8421 to your computer and use it in GitHub Desktop.
Save leonjza/f35a7252babdf77c8421 to your computer and use it in GitHub Desktop.
Python Netcat
import socket
class Netcat:
""" Python 'netcat like' module """
def __init__(self, ip, port):
self.buff = ""
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((ip, port))
def read(self, length = 1024):
""" Read 1024 bytes off the socket """
return self.socket.recv(length)
def read_until(self, data):
""" Read data into the buffer until we have data """
while not data in self.buff:
self.buff += self.socket.recv(1024)
pos = self.buff.find(data)
rval = self.buff[:pos + len(data)]
self.buff = self.buff[pos + len(data):]
return rval
def write(self, data):
def close(self):
# below is a extract from a sample exploit that
# interfaces with a tcp socket
from netcat import Netcat
# start a new Netcat() instance
nc = Netcat('', 53121)
# get to the prompt
# start a new note
nc.write('new' + '\n')
# set note 0 with the payload
nc.write('set' + '\n')
Copy link

kolayne commented Sep 13, 2018

im getting this error
Traceback (most recent call last):
File "C:\Users\magshimim\Desktop\", line 62, in
File "C:\Users\magshimim\Desktop\", line 46, in main
output = nc.read_until(":")
File "C:\Users\magshimim\Desktop\", line 24, in read_until
self.buff += self.socket.recv(1024)
TypeError: must be str, not bytes

can you tell what it means?

Replace line 9 with self.buff = b''
And use output = nc.read_until(b":") instead of output = nc.read_until(":") in your code

Copy link

With the above scripts is it also possible to receive the data, after this send a reaction en receive the next message and so on and on?
How could I realise this and does some one have a example script for this?

Copy link

why sometimes does it take a long time to read the response?

Copy link

bw0rth commented Apr 1, 2022

Hi, just in case anyone here is interested, I've recently made a Netcat library for Python.
Here is the GitHub repo for the project if you want to check it out.

Please note that it is still in early development and if anyone has any feedback or suggestions please let me know.
Thank you 😊

Copy link

this is worst implementation! it doesn't work in various situations. It's not doing what NC's job is.

Copy link

@brenw0rth exactly what I need, thanks:)

Copy link

bw0rth commented Mar 7, 2023

@brenw0rth exactly what I need, thanks:)

You're welcome :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment