【问题标题】:Python telnet connection failurePython telnet 连接失败
【发布时间】:2017-12-20 00:55:54
【问题描述】:

我有接受 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")

它总是命中例外。

当我尝试导入 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)

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

【问题讨论】:

  • 错误很明显,需要你指明端口。
  • 端口不应该默认为23吗?
  • telnet = Telnet() , telnet.open(host, port) 。从错误中可以明显看出 open 不是静态方法
  • 我想我明白了。这两个问题都源于Telnet.open(...)。您需要先创建一个实例,然后在该实例上调用openwrite。查看lungj的回答
  • @eyllanesc quamrana 说了什么:the port number defaults to the standard Telnet port (23)。但最好避免使用.open方法,直接使用telnetlib.Telnet构造函数打开连接。

标签: python python-2.7 python-3.x telnet


【解决方案1】:

需要调用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

【讨论】:

  • 使用纯except 子句不是一个好主意。明确命名您要捕获的异常!
  • @PM2Ring 真;我刚刚修改了 OP 的代码以解决所面临的问题。我至少会稍微改进一下编辑中的代码。
  • 您是否看到“无法建立连接”?如果出现连接错误,telnet_obj 将不会被定义,您将收到该特定错误。因此,如果遇到连接错误,您必须从函数返回或重新引发异常。
  • @Mike.G lungj 的代码不是一个完整的解决方案:它忽略 错误。您可以在print("Connection cannot be established") 之后放置raise 语句,以便代码在执行print 调用后中止(并显示错误消息)。但是,如果您收到“无法建立连接”消息,则需要验证主机字符串和端口号是否正确。
  • @PM2Ring 所说的 :) 此外,我稍微更新了打印异常跟踪的答案,以帮助您进行故障排除。
猜你喜欢
  • 2022-08-14
  • 2017-09-29
  • 2012-04-03
  • 2011-05-30
  • 2011-12-07
  • 2022-11-19
  • 1970-01-01
  • 2016-10-17
相关资源
最近更新 更多