【问题标题】:Why does telnet work and netcat fail with this Twisted example?为什么 telnet 可以工作,而 netcat 在这个 Twisted 示例中会失败?
【发布时间】:2016-06-28 06:53:52
【问题描述】:

我正在关注Twisted tutorial并尝试了该文章中的以下代码:

# Read username, output from non-empty factory, drop connections

from twisted.internet import protocol, reactor
from twisted.protocols import basic

class FingerProtocol(basic.LineReceiver):
    def lineReceived(self, user):
        self.transport.write(self.factory.getUser(user)+"\r\n")
        self.transport.loseConnection()

class FingerFactory(protocol.ServerFactory):
    protocol = FingerProtocol

    def __init__(self, **kwargs):
        self.users = kwargs

    def getUser(self, user):
        return self.users.get(user, "No such user")

reactor.listenTCP(1079, FingerFactory(moshez='Happy and well'))
reactor.run()

我尝试了nc localhost 1079,但它只是挂起:没有回复。但是telnet localhost 1079 工作得很好。为什么?

【问题讨论】:

    标签: python twisted telnet netcat


    【解决方案1】:

    使用wireshark,我发现了以下内容:telnet 发送0x0d,然后发送0x0a(即“\r\n”)作为行终止符。然而netcat 只发送了 0x0a。这是在 Ubuntu(以及 OS X)上。

    显然,Twisted 中的 LineReceiver 协议需要 \r 才能引发“line received”事件。

    netcat 至少有 6 个版本,但 OS X(接近 FreeBSD)上的版本有一个 -c 选项,将 \r\n 附加到每一行的末尾。使用此选项可以解决问题。

    $ nc -c localhost 1079 
    moshez
    Happy and well
    

    注意:LineReceiver 有一个名为 delimiter 的类变量,它允许使用任何 EOL 字符。设置 delimiter = '\n' 可以避免 netcat 需要 -c 选项。

    【讨论】:

    • 这是 100% 正确的答案,所以你应该接受你自己的答案 :)
    • 该网站要求我等待 2 天才能这样做。 :)
    【解决方案2】:

    在linux上,你需要使用CRLF作为EOL

    来自 nc 手册页:

    -C, --crlf(使用 CRLF 作为 EOL)。 这个选项告诉 Ncat 转换 LF。 CRLF 的行尾。当从标准输入中获取输入时。这对于直接从终端以使用 CRLF 作为行尾的许多常见纯文本协议之一的终端与某些严格的服务器通信很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-13
      • 2014-06-19
      • 2011-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多