gpt4 book ai didi

Python telnet 连接失败

转载 作者:行者123 更新时间:2023-12-01 02:47:40 24 4
gpt4 key购买 nike

我有接受 telnet 连接的设备,可以通过 AT 命令使用它

这是我的代码,我相信应该很简单,但由于某种原因它无法工作,我对 telnet lib 相当陌生,所以我不明白我在这里缺少什么

def connect(self, host, port):
try:
Telnet.open(host, port)
Telnet.write('AT'+"\r")
if Telnet.read_until("OK"):
print("You are connected")
except:
print("Connection cannot be established")

它总是命中异常(exception)。

当我尝试导入 telnetlib 并仅使用没有端口的 IP 运行它时,我也收到以下错误。

Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
Telnet.open('192.168.0.1')
TypeError: unbound method open() must be called with Telnet instance as
first argument (got str instance instead)

我无法理解它要我做什么。

最佳答案

需要调用 Telnet 类的构造函数:

import traceback

def connect(self, host, port):
try:
telnet_obj = Telnet(host, port) # Use the constructor instead of the open() method.
except Exception as e: # Should explicitly list exceptions to be caught. Also, only include the minimum code where you can handle the error.
print("Connection cannot be established")
traceback.print_exc() # Get a traceback of the error.
# Do further error handling here and return/reraise.

# This code is unrelated to opening a connection, so your error
# handler for establishing a connection should not be run if
# write() or read_until() raise an error.
telnet_obj.write('AT'+"\r") # then use the returned object's methods.
if telnet_obj.read_until("OK"):
print("You are connected")

相关:Python newbie having a problem using classes

关于Python telnet 连接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45111166/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com