简体   繁体   中英

Simple python telnet client/server example doesn't work

I'm trying to create mockup telnet server (for some functional testing of existing code). Right now I only modified server welcome message and I was trying to read this message using client code, but it read method fails on timeout with no additional info. But with pudb debugger enabled it works most of the time...

I'm using virtualenv, with pudb and telnetsrv installed using pip. Python 2.7.12, ubuntu 16.04.

Server code:

import SocketServer
from telnetsrv.threaded import TelnetHandler

class MyHandler(TelnetHandler):

    WELCOME = "HI from custom server"

class TelnetServer(SocketServer.TCPServer):
    allow_reuse_address = True

server = TelnetServer(("0.0.0.0", 8023), MyHandler)
server.serve_forever()

Client code:

import telnetlib

HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)

data = tn.read_until("custom server", timeout=1)
print "Data: " + data

tn.close()

Client output:

$ python client.py
Data:

Client output with pudb enabled (with step-by-step execution)

$ python client.py
Data: HI from custom server

Of course when I execute shell telnet command, it all works fine:

$ telnet 127.0.0.1 8023
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
HI from custom server
Telnet Server> 

I'd really appreciate any hints on how to debug this problem. Thanks!

Be sure there is actually connecting going on. To do that put edit your code to add tn.set_debuglevel(100) into your script to look like this:

import telnetlib

HOST = '127.0.0.1'
PORT = 8023
# from pudb import set_trace; set_trace()
tn = telnetlib.Telnet(HOST, PORT)
tn.set_debuglevel(100)
data = tn.read_until("custom server", timeout=1)
print "Data: " + data

tn.close()

This will ensure all the data is printed out so you can see what's going on.

My theory is, that you're not connecting, or that your data isn't actually outputting "custom server" and therefor it won't catch it, or your timeout is too low.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM