Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Netcat implementation in Python

Tags:

python

netcat

I found this and am using it as my base, but it wasn't working right out of the box. My goal is also to treat it as a package instead of a command line utility, so my code changes will reflect that.

class Netcat:
    def __init__(self, hostname, port):
        self.hostname = hostname
        self.port = port
    def send(self, content):
    self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.socket.connect((self.hostname, self.port))
    self.socket.setblocking(0)
    result = '';
    read_ready, write_ready, in_error = select.select([self.socket], [], [self.socket], 5)
    if(self.socket.sendall(content) != None):
        return
    while(1):
        buffer = ''
        try:                
            buffer = self.socket.recv(128)
            while(buffer != ''):
                result += buffer
                try:
                    buffer = self.socket.recv(128)
                except socket.error as err:
                    print (err, type(err))
                    buffer = ''
            if(buffer == ''):
                break
        except socket.error as err:
            print (err, type(err))
        if(buffer == ''):
            break
    return result

When I send a basic command to my device, it returns the following.

50PMA-019 Connection Open
Atten #1 = 63dB

My code reads the first line, but then I get an error saying that the connection is temporarily unavailable and it does not get the second line. If I change it to blocking, it just blocks and never returns. Any thoughts?

like image 387
unholysampler Avatar asked Dec 15 '09 17:12

unholysampler


People also ask

What is netcat and how is it used?

netcat (often abbreviated to nc) is a computer networking utility for reading from and writing to network connections using TCP or UDP. The command is designed to be a dependable back-end that can be used directly or easily driven by other programs and scripts.

What is socket socket in python?

Sockets are the endpoints of a bidirectional communications channel. Sockets may communicate within a process, between processes on the same machine, or between processes on different continents. Sockets may be implemented over a number of different channel types: Unix domain sockets, TCP, UDP, and so on.


3 Answers

Does it work if you just use nc?

I think you should try something a little simpler:

import socket  def netcat(hostname, port, content):     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     s.connect((hostname, port))     s.sendall(content)     s.shutdown(socket.SHUT_WR)     while 1:         data = s.recv(1024)         if len(data) == 0:             break         print("Received:", repr(data))     print("Connection closed.")     s.close() 

I added the shutdown call because maybe your device is waiting for you to say you're done sending data. (That would be a little weird, but it's possible.)

like image 162
Jason Orendorff Avatar answered Sep 19 '22 16:09

Jason Orendorff


The following is a working implementation on python3:

import socket  def netcat(host, port, content):     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)     s.connect((host, int(port)))     s.sendall(content.encode())     s.shutdown(socket.SHUT_WR)     while True:         data = s.recv(4096)         if not data:             break         print(repr(data))     s.close() 

It can be used to send "content" to a "host" on "port" (which all might be entered as sting).

Regards

like image 23
d0n Avatar answered Sep 21 '22 16:09

d0n


if you don't mind scrapping that code altogether, you might like to look at scapy -- it's basically the swiss army knife of packet tools in python. take a look at the interactive tutorial to see if it fits your needs.

if you'd like something higher-level than packets twisted is the go-to library for networking in python... unfortunately the learning curve is a tad steep.

like image 22
Autoplectic Avatar answered Sep 20 '22 16:09

Autoplectic