Issue 1730959: telnetlib: A callback for monitoring the telnet session (original) (raw)

When automating a telnet session, you often want to know in realtime what is happening on an active connection. Currently, telnetlib provides the following way to monitor the session:


import sys, getpass from telnetlib import Telnet

HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass()

tn = Telnet(HOST) tn.read_until("login: ") tn.write(user + "\n")

if password: tn.read_until("Password: ") tn.write(password + "\n")

tn.write("ls\n") tn.write("exit\n")

In this case, the last line prints what happened on the session. Often times, you want to watch the session in realtime instead, but telnetlib does not provide a way to do this (AFAIK). I would like to see a callback added into libtelnet, letting you hook into the session such that the following code works:


import sys, getpass from telnetlib import Telnet

HOST = "localhost" user = raw_input("Enter your remote account: ") password = getpass.getpass()

def filter_cb(session, data): sys.stdout.write(data) return data

tn = Telnet(HOST) tn.set_data_filter_callback(filter_cb) tn.read_until("login: ") tn.write(user + "\n")

if password: tn.read_until("Password: ") tn.write(password + "\n")

tn.write("ls\n") tn.write("exit\n") tn.read_until("logout")

The attached patch (against SVN) implements this behavior. By taking the return value to replace the original data the callback can also be used to implement filters. This is nice for adapting the behavior of a remote machine, for example for filtering out unwanted characters.

This is my first patch against Python libraries, so apologies if I missed a guideline.