Python 中的 Netcat 实现

发布于 2024-08-14 18:40:17 字数 1513 浏览 5 评论 0原文

我发现 这个 并使用它作为我的基础,但它不能立即使用。我的目标是将其视为一个包而不是命令行实用程序,因此我的代码更改将反映这一点。

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

当我向我的设备发送基本命令时,它会返回以下内容。

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

我的代码读取第一行,但随后出现错误,指出连接暂时不可用,并且无法获取第二行。如果我将其更改为阻塞,它只会阻塞并且永远不会返回。有什么想法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

数理化全能战士 2024-08-21 18:40:17

如果您只使用 nc 是否有效?

我认为您应该尝试一些更简单的方法:

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()

我添加了 shutdown 调用,因为也许您的设备正在等待您说已完成发送数据。 (这有点奇怪,但这是可能的。)

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.)

青芜 2024-08-21 18:40:17

以下是 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()

它可用于将“内容”发送到“端口”上的“主机”(所有这些都可以作为字符串输入)。

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 string).

盗琴音 2024-08-21 18:40:17

如果您不介意完全废弃该代码,您可能想看看 scapy --它基本上是Python中数据包工具中的瑞士军刀。查看交互式教程看看是否可以适合您的需求。

如果你想要比数据包更高级别的东西twisted是Python中网络的首选库..不幸的是,学习曲线有点陡峭。

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.

方觉久 2024-08-21 18:40:17
import socket
import codecs
import subprocess

i = 0
sock = socket.socket()
host = ''
port = 
sock.connect((host, port))

while i != 20003:
  data = sock.recv(1024)
  print(data)
  data = codecs.escape_decode(data)[0].decode('unicode-escape')
  print(data)
  print(data.split())
  a = data.split()
  i +=1
import socket
import codecs
import subprocess

i = 0
sock = socket.socket()
host = ''
port = 
sock.connect((host, port))

while i != 20003:
  data = sock.recv(1024)
  print(data)
  data = codecs.escape_decode(data)[0].decode('unicode-escape')
  print(data)
  print(data.split())
  a = data.split()
  i +=1
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文