I'm working on making this Netcat replacement work. It's not my code, but I would like to fix it. Here's the code:
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):
self.socket.send(data)
def close(self):
self.socket.close()
# start a new Netcat() instance
nc = Netcat('192.168.0.1', 80)
# get to the prompt
nc.read_until('>')
# start a new note
nc.write('new' + '\n')
nc.read_until('>')
I've tried adding a new line above line 24 and encoding the string (using .encode('utf-8')
), but that didn't work. Any ideas? I believe the issue is something to do with how socket recv/send operations return/accept byte objects instead of strings, but I don't know how.