Python socket 实现的 Telnet 服务器数据回显格式问题

2022-10-22 12:56:02 +08:00
 CrystalMoling

我尝试使用 Python 中的 socket 创建 Telnet 服务器,并使用 Telnet 进行远程控制。但是当我使用 send() 在 Telnet 客户端回显数据时,换行的数据会从上一行的末尾开始显示,就像

第一行
     第二行
          第三行

有没有办法能够让后面的行从一行的开头开始显示?

目前的代码:

class Telnet(threading.Thread):
    def __init__(self, conn, add):
        threading.Thread.__init__(self)
        self.inputstr = ''
        self.connection = conn
        self.address = add
    def run(self):
        ii = 0
        self.connection.send(b'Hello controller')
        self.connection.send(b'\n>')
        while True:
            buf = self.connection.recv(1024)
            if buf.rfind(b'\n') > -1:
                print("**-" + self.inputstr)
                return_arr = self.inputstr.split(' ')
                match return_arr[0]:
                    case 'list':
                        func_return = list_connections()
                        for key in func_return.keys():
                            self.connection.send(key.encode())
                self.inputstr = ''
                self.connection.send(b'\n>')
            else:
                self.inputstr += buf.decode()
            if ii == 0:
                self.connection.send(buf)
            ii += 1
            continue
1256 次点击
所在节点    Python
1 条回复
ysc3839
2022-10-22 13:05:32 +08:00
telnet 协议的换行是 CRLF ,需要回车符(CR)把输出位置移动到行首

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/888920

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX