| 1 | n/a | r"""TELNET client class. |
|---|
| 2 | n/a | |
|---|
| 3 | n/a | Based on RFC 854: TELNET Protocol Specification, by J. Postel and |
|---|
| 4 | n/a | J. Reynolds |
|---|
| 5 | n/a | |
|---|
| 6 | n/a | Example: |
|---|
| 7 | n/a | |
|---|
| 8 | n/a | >>> from telnetlib import Telnet |
|---|
| 9 | n/a | >>> tn = Telnet('www.python.org', 79) # connect to finger port |
|---|
| 10 | n/a | >>> tn.write(b'guido\r\n') |
|---|
| 11 | n/a | >>> print(tn.read_all()) |
|---|
| 12 | n/a | Login Name TTY Idle When Where |
|---|
| 13 | n/a | guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston.. |
|---|
| 14 | n/a | |
|---|
| 15 | n/a | >>> |
|---|
| 16 | n/a | |
|---|
| 17 | n/a | Note that read_all() won't read until eof -- it just reads some data |
|---|
| 18 | n/a | -- but it guarantees to read at least one byte unless EOF is hit. |
|---|
| 19 | n/a | |
|---|
| 20 | n/a | It is possible to pass a Telnet object to a selector in order to wait until |
|---|
| 21 | n/a | more data is available. Note that in this case, read_eager() may return b'' |
|---|
| 22 | n/a | even if there was data on the socket, because the protocol negotiation may have |
|---|
| 23 | n/a | eaten the data. This is why EOFError is needed in some cases to distinguish |
|---|
| 24 | n/a | between "no data" and "connection closed" (since the socket also appears ready |
|---|
| 25 | n/a | for reading when it is closed). |
|---|
| 26 | n/a | |
|---|
| 27 | n/a | To do: |
|---|
| 28 | n/a | - option negotiation |
|---|
| 29 | n/a | - timeout should be intrinsic to the connection object instead of an |
|---|
| 30 | n/a | option on one of the read calls only |
|---|
| 31 | n/a | |
|---|
| 32 | n/a | """ |
|---|
| 33 | n/a | |
|---|
| 34 | n/a | |
|---|
| 35 | n/a | # Imported modules |
|---|
| 36 | n/a | import sys |
|---|
| 37 | n/a | import socket |
|---|
| 38 | n/a | import selectors |
|---|
| 39 | n/a | from time import monotonic as _time |
|---|
| 40 | n/a | |
|---|
| 41 | n/a | __all__ = ["Telnet"] |
|---|
| 42 | n/a | |
|---|
| 43 | n/a | # Tunable parameters |
|---|
| 44 | n/a | DEBUGLEVEL = 0 |
|---|
| 45 | n/a | |
|---|
| 46 | n/a | # Telnet protocol defaults |
|---|
| 47 | n/a | TELNET_PORT = 23 |
|---|
| 48 | n/a | |
|---|
| 49 | n/a | # Telnet protocol characters (don't change) |
|---|
| 50 | n/a | IAC = bytes([255]) # "Interpret As Command" |
|---|
| 51 | n/a | DONT = bytes([254]) |
|---|
| 52 | n/a | DO = bytes([253]) |
|---|
| 53 | n/a | WONT = bytes([252]) |
|---|
| 54 | n/a | WILL = bytes([251]) |
|---|
| 55 | n/a | theNULL = bytes([0]) |
|---|
| 56 | n/a | |
|---|
| 57 | n/a | SE = bytes([240]) # Subnegotiation End |
|---|
| 58 | n/a | NOP = bytes([241]) # No Operation |
|---|
| 59 | n/a | DM = bytes([242]) # Data Mark |
|---|
| 60 | n/a | BRK = bytes([243]) # Break |
|---|
| 61 | n/a | IP = bytes([244]) # Interrupt process |
|---|
| 62 | n/a | AO = bytes([245]) # Abort output |
|---|
| 63 | n/a | AYT = bytes([246]) # Are You There |
|---|
| 64 | n/a | EC = bytes([247]) # Erase Character |
|---|
| 65 | n/a | EL = bytes([248]) # Erase Line |
|---|
| 66 | n/a | GA = bytes([249]) # Go Ahead |
|---|
| 67 | n/a | SB = bytes([250]) # Subnegotiation Begin |
|---|
| 68 | n/a | |
|---|
| 69 | n/a | |
|---|
| 70 | n/a | # Telnet protocol options code (don't change) |
|---|
| 71 | n/a | # These ones all come from arpa/telnet.h |
|---|
| 72 | n/a | BINARY = bytes([0]) # 8-bit data path |
|---|
| 73 | n/a | ECHO = bytes([1]) # echo |
|---|
| 74 | n/a | RCP = bytes([2]) # prepare to reconnect |
|---|
| 75 | n/a | SGA = bytes([3]) # suppress go ahead |
|---|
| 76 | n/a | NAMS = bytes([4]) # approximate message size |
|---|
| 77 | n/a | STATUS = bytes([5]) # give status |
|---|
| 78 | n/a | TM = bytes([6]) # timing mark |
|---|
| 79 | n/a | RCTE = bytes([7]) # remote controlled transmission and echo |
|---|
| 80 | n/a | NAOL = bytes([8]) # negotiate about output line width |
|---|
| 81 | n/a | NAOP = bytes([9]) # negotiate about output page size |
|---|
| 82 | n/a | NAOCRD = bytes([10]) # negotiate about CR disposition |
|---|
| 83 | n/a | NAOHTS = bytes([11]) # negotiate about horizontal tabstops |
|---|
| 84 | n/a | NAOHTD = bytes([12]) # negotiate about horizontal tab disposition |
|---|
| 85 | n/a | NAOFFD = bytes([13]) # negotiate about formfeed disposition |
|---|
| 86 | n/a | NAOVTS = bytes([14]) # negotiate about vertical tab stops |
|---|
| 87 | n/a | NAOVTD = bytes([15]) # negotiate about vertical tab disposition |
|---|
| 88 | n/a | NAOLFD = bytes([16]) # negotiate about output LF disposition |
|---|
| 89 | n/a | XASCII = bytes([17]) # extended ascii character set |
|---|
| 90 | n/a | LOGOUT = bytes([18]) # force logout |
|---|
| 91 | n/a | BM = bytes([19]) # byte macro |
|---|
| 92 | n/a | DET = bytes([20]) # data entry terminal |
|---|
| 93 | n/a | SUPDUP = bytes([21]) # supdup protocol |
|---|
| 94 | n/a | SUPDUPOUTPUT = bytes([22]) # supdup output |
|---|
| 95 | n/a | SNDLOC = bytes([23]) # send location |
|---|
| 96 | n/a | TTYPE = bytes([24]) # terminal type |
|---|
| 97 | n/a | EOR = bytes([25]) # end or record |
|---|
| 98 | n/a | TUID = bytes([26]) # TACACS user identification |
|---|
| 99 | n/a | OUTMRK = bytes([27]) # output marking |
|---|
| 100 | n/a | TTYLOC = bytes([28]) # terminal location number |
|---|
| 101 | n/a | VT3270REGIME = bytes([29]) # 3270 regime |
|---|
| 102 | n/a | X3PAD = bytes([30]) # X.3 PAD |
|---|
| 103 | n/a | NAWS = bytes([31]) # window size |
|---|
| 104 | n/a | TSPEED = bytes([32]) # terminal speed |
|---|
| 105 | n/a | LFLOW = bytes([33]) # remote flow control |
|---|
| 106 | n/a | LINEMODE = bytes([34]) # Linemode option |
|---|
| 107 | n/a | XDISPLOC = bytes([35]) # X Display Location |
|---|
| 108 | n/a | OLD_ENVIRON = bytes([36]) # Old - Environment variables |
|---|
| 109 | n/a | AUTHENTICATION = bytes([37]) # Authenticate |
|---|
| 110 | n/a | ENCRYPT = bytes([38]) # Encryption option |
|---|
| 111 | n/a | NEW_ENVIRON = bytes([39]) # New - Environment variables |
|---|
| 112 | n/a | # the following ones come from |
|---|
| 113 | n/a | # http://www.iana.org/assignments/telnet-options |
|---|
| 114 | n/a | # Unfortunately, that document does not assign identifiers |
|---|
| 115 | n/a | # to all of them, so we are making them up |
|---|
| 116 | n/a | TN3270E = bytes([40]) # TN3270E |
|---|
| 117 | n/a | XAUTH = bytes([41]) # XAUTH |
|---|
| 118 | n/a | CHARSET = bytes([42]) # CHARSET |
|---|
| 119 | n/a | RSP = bytes([43]) # Telnet Remote Serial Port |
|---|
| 120 | n/a | COM_PORT_OPTION = bytes([44]) # Com Port Control Option |
|---|
| 121 | n/a | SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo |
|---|
| 122 | n/a | TLS = bytes([46]) # Telnet Start TLS |
|---|
| 123 | n/a | KERMIT = bytes([47]) # KERMIT |
|---|
| 124 | n/a | SEND_URL = bytes([48]) # SEND-URL |
|---|
| 125 | n/a | FORWARD_X = bytes([49]) # FORWARD_X |
|---|
| 126 | n/a | PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON |
|---|
| 127 | n/a | SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON |
|---|
| 128 | n/a | PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT |
|---|
| 129 | n/a | EXOPL = bytes([255]) # Extended-Options-List |
|---|
| 130 | n/a | NOOPT = bytes([0]) |
|---|
| 131 | n/a | |
|---|
| 132 | n/a | |
|---|
| 133 | n/a | # poll/select have the advantage of not requiring any extra file descriptor, |
|---|
| 134 | n/a | # contrarily to epoll/kqueue (also, they require a single syscall). |
|---|
| 135 | n/a | if hasattr(selectors, 'PollSelector'): |
|---|
| 136 | n/a | _TelnetSelector = selectors.PollSelector |
|---|
| 137 | n/a | else: |
|---|
| 138 | n/a | _TelnetSelector = selectors.SelectSelector |
|---|
| 139 | n/a | |
|---|
| 140 | n/a | |
|---|
| 141 | n/a | class Telnet: |
|---|
| 142 | n/a | |
|---|
| 143 | n/a | """Telnet interface class. |
|---|
| 144 | n/a | |
|---|
| 145 | n/a | An instance of this class represents a connection to a telnet |
|---|
| 146 | n/a | server. The instance is initially not connected; the open() |
|---|
| 147 | n/a | method must be used to establish a connection. Alternatively, the |
|---|
| 148 | n/a | host name and optional port number can be passed to the |
|---|
| 149 | n/a | constructor, too. |
|---|
| 150 | n/a | |
|---|
| 151 | n/a | Don't try to reopen an already connected instance. |
|---|
| 152 | n/a | |
|---|
| 153 | n/a | This class has many read_*() methods. Note that some of them |
|---|
| 154 | n/a | raise EOFError when the end of the connection is read, because |
|---|
| 155 | n/a | they can return an empty string for other reasons. See the |
|---|
| 156 | n/a | individual doc strings. |
|---|
| 157 | n/a | |
|---|
| 158 | n/a | read_until(expected, [timeout]) |
|---|
| 159 | n/a | Read until the expected string has been seen, or a timeout is |
|---|
| 160 | n/a | hit (default is no timeout); may block. |
|---|
| 161 | n/a | |
|---|
| 162 | n/a | read_all() |
|---|
| 163 | n/a | Read all data until EOF; may block. |
|---|
| 164 | n/a | |
|---|
| 165 | n/a | read_some() |
|---|
| 166 | n/a | Read at least one byte or EOF; may block. |
|---|
| 167 | n/a | |
|---|
| 168 | n/a | read_very_eager() |
|---|
| 169 | n/a | Read all data available already queued or on the socket, |
|---|
| 170 | n/a | without blocking. |
|---|
| 171 | n/a | |
|---|
| 172 | n/a | read_eager() |
|---|
| 173 | n/a | Read either data already queued or some data available on the |
|---|
| 174 | n/a | socket, without blocking. |
|---|
| 175 | n/a | |
|---|
| 176 | n/a | read_lazy() |
|---|
| 177 | n/a | Read all data in the raw queue (processing it first), without |
|---|
| 178 | n/a | doing any socket I/O. |
|---|
| 179 | n/a | |
|---|
| 180 | n/a | read_very_lazy() |
|---|
| 181 | n/a | Reads all data in the cooked queue, without doing any socket |
|---|
| 182 | n/a | I/O. |
|---|
| 183 | n/a | |
|---|
| 184 | n/a | read_sb_data() |
|---|
| 185 | n/a | Reads available data between SB ... SE sequence. Don't block. |
|---|
| 186 | n/a | |
|---|
| 187 | n/a | set_option_negotiation_callback(callback) |
|---|
| 188 | n/a | Each time a telnet option is read on the input flow, this callback |
|---|
| 189 | n/a | (if set) is called with the following parameters : |
|---|
| 190 | n/a | callback(telnet socket, command, option) |
|---|
| 191 | n/a | option will be chr(0) when there is no option. |
|---|
| 192 | n/a | No other action is done afterwards by telnetlib. |
|---|
| 193 | n/a | |
|---|
| 194 | n/a | """ |
|---|
| 195 | n/a | |
|---|
| 196 | n/a | def __init__(self, host=None, port=0, |
|---|
| 197 | n/a | timeout=socket._GLOBAL_DEFAULT_TIMEOUT): |
|---|
| 198 | n/a | """Constructor. |
|---|
| 199 | n/a | |
|---|
| 200 | n/a | When called without arguments, create an unconnected instance. |
|---|
| 201 | n/a | With a hostname argument, it connects the instance; port number |
|---|
| 202 | n/a | and timeout are optional. |
|---|
| 203 | n/a | """ |
|---|
| 204 | n/a | self.debuglevel = DEBUGLEVEL |
|---|
| 205 | n/a | self.host = host |
|---|
| 206 | n/a | self.port = port |
|---|
| 207 | n/a | self.timeout = timeout |
|---|
| 208 | n/a | self.sock = None |
|---|
| 209 | n/a | self.rawq = b'' |
|---|
| 210 | n/a | self.irawq = 0 |
|---|
| 211 | n/a | self.cookedq = b'' |
|---|
| 212 | n/a | self.eof = 0 |
|---|
| 213 | n/a | self.iacseq = b'' # Buffer for IAC sequence. |
|---|
| 214 | n/a | self.sb = 0 # flag for SB and SE sequence. |
|---|
| 215 | n/a | self.sbdataq = b'' |
|---|
| 216 | n/a | self.option_callback = None |
|---|
| 217 | n/a | if host is not None: |
|---|
| 218 | n/a | self.open(host, port, timeout) |
|---|
| 219 | n/a | |
|---|
| 220 | n/a | def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT): |
|---|
| 221 | n/a | """Connect to a host. |
|---|
| 222 | n/a | |
|---|
| 223 | n/a | The optional second argument is the port number, which |
|---|
| 224 | n/a | defaults to the standard telnet port (23). |
|---|
| 225 | n/a | |
|---|
| 226 | n/a | Don't try to reopen an already connected instance. |
|---|
| 227 | n/a | """ |
|---|
| 228 | n/a | self.eof = 0 |
|---|
| 229 | n/a | if not port: |
|---|
| 230 | n/a | port = TELNET_PORT |
|---|
| 231 | n/a | self.host = host |
|---|
| 232 | n/a | self.port = port |
|---|
| 233 | n/a | self.timeout = timeout |
|---|
| 234 | n/a | self.sock = socket.create_connection((host, port), timeout) |
|---|
| 235 | n/a | |
|---|
| 236 | n/a | def __del__(self): |
|---|
| 237 | n/a | """Destructor -- close the connection.""" |
|---|
| 238 | n/a | self.close() |
|---|
| 239 | n/a | |
|---|
| 240 | n/a | def msg(self, msg, *args): |
|---|
| 241 | n/a | """Print a debug message, when the debug level is > 0. |
|---|
| 242 | n/a | |
|---|
| 243 | n/a | If extra arguments are present, they are substituted in the |
|---|
| 244 | n/a | message using the standard string formatting operator. |
|---|
| 245 | n/a | |
|---|
| 246 | n/a | """ |
|---|
| 247 | n/a | if self.debuglevel > 0: |
|---|
| 248 | n/a | print('Telnet(%s,%s):' % (self.host, self.port), end=' ') |
|---|
| 249 | n/a | if args: |
|---|
| 250 | n/a | print(msg % args) |
|---|
| 251 | n/a | else: |
|---|
| 252 | n/a | print(msg) |
|---|
| 253 | n/a | |
|---|
| 254 | n/a | def set_debuglevel(self, debuglevel): |
|---|
| 255 | n/a | """Set the debug level. |
|---|
| 256 | n/a | |
|---|
| 257 | n/a | The higher it is, the more debug output you get (on sys.stdout). |
|---|
| 258 | n/a | |
|---|
| 259 | n/a | """ |
|---|
| 260 | n/a | self.debuglevel = debuglevel |
|---|
| 261 | n/a | |
|---|
| 262 | n/a | def close(self): |
|---|
| 263 | n/a | """Close the connection.""" |
|---|
| 264 | n/a | sock = self.sock |
|---|
| 265 | n/a | self.sock = None |
|---|
| 266 | n/a | self.eof = True |
|---|
| 267 | n/a | self.iacseq = b'' |
|---|
| 268 | n/a | self.sb = 0 |
|---|
| 269 | n/a | if sock: |
|---|
| 270 | n/a | sock.close() |
|---|
| 271 | n/a | |
|---|
| 272 | n/a | def get_socket(self): |
|---|
| 273 | n/a | """Return the socket object used internally.""" |
|---|
| 274 | n/a | return self.sock |
|---|
| 275 | n/a | |
|---|
| 276 | n/a | def fileno(self): |
|---|
| 277 | n/a | """Return the fileno() of the socket object used internally.""" |
|---|
| 278 | n/a | return self.sock.fileno() |
|---|
| 279 | n/a | |
|---|
| 280 | n/a | def write(self, buffer): |
|---|
| 281 | n/a | """Write a string to the socket, doubling any IAC characters. |
|---|
| 282 | n/a | |
|---|
| 283 | n/a | Can block if the connection is blocked. May raise |
|---|
| 284 | n/a | OSError if the connection is closed. |
|---|
| 285 | n/a | |
|---|
| 286 | n/a | """ |
|---|
| 287 | n/a | if IAC in buffer: |
|---|
| 288 | n/a | buffer = buffer.replace(IAC, IAC+IAC) |
|---|
| 289 | n/a | self.msg("send %r", buffer) |
|---|
| 290 | n/a | self.sock.sendall(buffer) |
|---|
| 291 | n/a | |
|---|
| 292 | n/a | def read_until(self, match, timeout=None): |
|---|
| 293 | n/a | """Read until a given string is encountered or until timeout. |
|---|
| 294 | n/a | |
|---|
| 295 | n/a | When no match is found, return whatever is available instead, |
|---|
| 296 | n/a | possibly the empty string. Raise EOFError if the connection |
|---|
| 297 | n/a | is closed and no cooked data is available. |
|---|
| 298 | n/a | |
|---|
| 299 | n/a | """ |
|---|
| 300 | n/a | n = len(match) |
|---|
| 301 | n/a | self.process_rawq() |
|---|
| 302 | n/a | i = self.cookedq.find(match) |
|---|
| 303 | n/a | if i >= 0: |
|---|
| 304 | n/a | i = i+n |
|---|
| 305 | n/a | buf = self.cookedq[:i] |
|---|
| 306 | n/a | self.cookedq = self.cookedq[i:] |
|---|
| 307 | n/a | return buf |
|---|
| 308 | n/a | if timeout is not None: |
|---|
| 309 | n/a | deadline = _time() + timeout |
|---|
| 310 | n/a | with _TelnetSelector() as selector: |
|---|
| 311 | n/a | selector.register(self, selectors.EVENT_READ) |
|---|
| 312 | n/a | while not self.eof: |
|---|
| 313 | n/a | if selector.select(timeout): |
|---|
| 314 | n/a | i = max(0, len(self.cookedq)-n) |
|---|
| 315 | n/a | self.fill_rawq() |
|---|
| 316 | n/a | self.process_rawq() |
|---|
| 317 | n/a | i = self.cookedq.find(match, i) |
|---|
| 318 | n/a | if i >= 0: |
|---|
| 319 | n/a | i = i+n |
|---|
| 320 | n/a | buf = self.cookedq[:i] |
|---|
| 321 | n/a | self.cookedq = self.cookedq[i:] |
|---|
| 322 | n/a | return buf |
|---|
| 323 | n/a | if timeout is not None: |
|---|
| 324 | n/a | timeout = deadline - _time() |
|---|
| 325 | n/a | if timeout < 0: |
|---|
| 326 | n/a | break |
|---|
| 327 | n/a | return self.read_very_lazy() |
|---|
| 328 | n/a | |
|---|
| 329 | n/a | def read_all(self): |
|---|
| 330 | n/a | """Read all data until EOF; block until connection closed.""" |
|---|
| 331 | n/a | self.process_rawq() |
|---|
| 332 | n/a | while not self.eof: |
|---|
| 333 | n/a | self.fill_rawq() |
|---|
| 334 | n/a | self.process_rawq() |
|---|
| 335 | n/a | buf = self.cookedq |
|---|
| 336 | n/a | self.cookedq = b'' |
|---|
| 337 | n/a | return buf |
|---|
| 338 | n/a | |
|---|
| 339 | n/a | def read_some(self): |
|---|
| 340 | n/a | """Read at least one byte of cooked data unless EOF is hit. |
|---|
| 341 | n/a | |
|---|
| 342 | n/a | Return b'' if EOF is hit. Block if no data is immediately |
|---|
| 343 | n/a | available. |
|---|
| 344 | n/a | |
|---|
| 345 | n/a | """ |
|---|
| 346 | n/a | self.process_rawq() |
|---|
| 347 | n/a | while not self.cookedq and not self.eof: |
|---|
| 348 | n/a | self.fill_rawq() |
|---|
| 349 | n/a | self.process_rawq() |
|---|
| 350 | n/a | buf = self.cookedq |
|---|
| 351 | n/a | self.cookedq = b'' |
|---|
| 352 | n/a | return buf |
|---|
| 353 | n/a | |
|---|
| 354 | n/a | def read_very_eager(self): |
|---|
| 355 | n/a | """Read everything that's possible without blocking in I/O (eager). |
|---|
| 356 | n/a | |
|---|
| 357 | n/a | Raise EOFError if connection closed and no cooked data |
|---|
| 358 | n/a | available. Return b'' if no cooked data available otherwise. |
|---|
| 359 | n/a | Don't block unless in the midst of an IAC sequence. |
|---|
| 360 | n/a | |
|---|
| 361 | n/a | """ |
|---|
| 362 | n/a | self.process_rawq() |
|---|
| 363 | n/a | while not self.eof and self.sock_avail(): |
|---|
| 364 | n/a | self.fill_rawq() |
|---|
| 365 | n/a | self.process_rawq() |
|---|
| 366 | n/a | return self.read_very_lazy() |
|---|
| 367 | n/a | |
|---|
| 368 | n/a | def read_eager(self): |
|---|
| 369 | n/a | """Read readily available data. |
|---|
| 370 | n/a | |
|---|
| 371 | n/a | Raise EOFError if connection closed and no cooked data |
|---|
| 372 | n/a | available. Return b'' if no cooked data available otherwise. |
|---|
| 373 | n/a | Don't block unless in the midst of an IAC sequence. |
|---|
| 374 | n/a | |
|---|
| 375 | n/a | """ |
|---|
| 376 | n/a | self.process_rawq() |
|---|
| 377 | n/a | while not self.cookedq and not self.eof and self.sock_avail(): |
|---|
| 378 | n/a | self.fill_rawq() |
|---|
| 379 | n/a | self.process_rawq() |
|---|
| 380 | n/a | return self.read_very_lazy() |
|---|
| 381 | n/a | |
|---|
| 382 | n/a | def read_lazy(self): |
|---|
| 383 | n/a | """Process and return data that's already in the queues (lazy). |
|---|
| 384 | n/a | |
|---|
| 385 | n/a | Raise EOFError if connection closed and no data available. |
|---|
| 386 | n/a | Return b'' if no cooked data available otherwise. Don't block |
|---|
| 387 | n/a | unless in the midst of an IAC sequence. |
|---|
| 388 | n/a | |
|---|
| 389 | n/a | """ |
|---|
| 390 | n/a | self.process_rawq() |
|---|
| 391 | n/a | return self.read_very_lazy() |
|---|
| 392 | n/a | |
|---|
| 393 | n/a | def read_very_lazy(self): |
|---|
| 394 | n/a | """Return any data available in the cooked queue (very lazy). |
|---|
| 395 | n/a | |
|---|
| 396 | n/a | Raise EOFError if connection closed and no data available. |
|---|
| 397 | n/a | Return b'' if no cooked data available otherwise. Don't block. |
|---|
| 398 | n/a | |
|---|
| 399 | n/a | """ |
|---|
| 400 | n/a | buf = self.cookedq |
|---|
| 401 | n/a | self.cookedq = b'' |
|---|
| 402 | n/a | if not buf and self.eof and not self.rawq: |
|---|
| 403 | n/a | raise EOFError('telnet connection closed') |
|---|
| 404 | n/a | return buf |
|---|
| 405 | n/a | |
|---|
| 406 | n/a | def read_sb_data(self): |
|---|
| 407 | n/a | """Return any data available in the SB ... SE queue. |
|---|
| 408 | n/a | |
|---|
| 409 | n/a | Return b'' if no SB ... SE available. Should only be called |
|---|
| 410 | n/a | after seeing a SB or SE command. When a new SB command is |
|---|
| 411 | n/a | found, old unread SB data will be discarded. Don't block. |
|---|
| 412 | n/a | |
|---|
| 413 | n/a | """ |
|---|
| 414 | n/a | buf = self.sbdataq |
|---|
| 415 | n/a | self.sbdataq = b'' |
|---|
| 416 | n/a | return buf |
|---|
| 417 | n/a | |
|---|
| 418 | n/a | def set_option_negotiation_callback(self, callback): |
|---|
| 419 | n/a | """Provide a callback function called after each receipt of a telnet option.""" |
|---|
| 420 | n/a | self.option_callback = callback |
|---|
| 421 | n/a | |
|---|
| 422 | n/a | def process_rawq(self): |
|---|
| 423 | n/a | """Transfer from raw queue to cooked queue. |
|---|
| 424 | n/a | |
|---|
| 425 | n/a | Set self.eof when connection is closed. Don't block unless in |
|---|
| 426 | n/a | the midst of an IAC sequence. |
|---|
| 427 | n/a | |
|---|
| 428 | n/a | """ |
|---|
| 429 | n/a | buf = [b'', b''] |
|---|
| 430 | n/a | try: |
|---|
| 431 | n/a | while self.rawq: |
|---|
| 432 | n/a | c = self.rawq_getchar() |
|---|
| 433 | n/a | if not self.iacseq: |
|---|
| 434 | n/a | if c == theNULL: |
|---|
| 435 | n/a | continue |
|---|
| 436 | n/a | if c == b"\021": |
|---|
| 437 | n/a | continue |
|---|
| 438 | n/a | if c != IAC: |
|---|
| 439 | n/a | buf[self.sb] = buf[self.sb] + c |
|---|
| 440 | n/a | continue |
|---|
| 441 | n/a | else: |
|---|
| 442 | n/a | self.iacseq += c |
|---|
| 443 | n/a | elif len(self.iacseq) == 1: |
|---|
| 444 | n/a | # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]' |
|---|
| 445 | n/a | if c in (DO, DONT, WILL, WONT): |
|---|
| 446 | n/a | self.iacseq += c |
|---|
| 447 | n/a | continue |
|---|
| 448 | n/a | |
|---|
| 449 | n/a | self.iacseq = b'' |
|---|
| 450 | n/a | if c == IAC: |
|---|
| 451 | n/a | buf[self.sb] = buf[self.sb] + c |
|---|
| 452 | n/a | else: |
|---|
| 453 | n/a | if c == SB: # SB ... SE start. |
|---|
| 454 | n/a | self.sb = 1 |
|---|
| 455 | n/a | self.sbdataq = b'' |
|---|
| 456 | n/a | elif c == SE: |
|---|
| 457 | n/a | self.sb = 0 |
|---|
| 458 | n/a | self.sbdataq = self.sbdataq + buf[1] |
|---|
| 459 | n/a | buf[1] = b'' |
|---|
| 460 | n/a | if self.option_callback: |
|---|
| 461 | n/a | # Callback is supposed to look into |
|---|
| 462 | n/a | # the sbdataq |
|---|
| 463 | n/a | self.option_callback(self.sock, c, NOOPT) |
|---|
| 464 | n/a | else: |
|---|
| 465 | n/a | # We can't offer automatic processing of |
|---|
| 466 | n/a | # suboptions. Alas, we should not get any |
|---|
| 467 | n/a | # unless we did a WILL/DO before. |
|---|
| 468 | n/a | self.msg('IAC %d not recognized' % ord(c)) |
|---|
| 469 | n/a | elif len(self.iacseq) == 2: |
|---|
| 470 | n/a | cmd = self.iacseq[1:2] |
|---|
| 471 | n/a | self.iacseq = b'' |
|---|
| 472 | n/a | opt = c |
|---|
| 473 | n/a | if cmd in (DO, DONT): |
|---|
| 474 | n/a | self.msg('IAC %s %d', |
|---|
| 475 | n/a | cmd == DO and 'DO' or 'DONT', ord(opt)) |
|---|
| 476 | n/a | if self.option_callback: |
|---|
| 477 | n/a | self.option_callback(self.sock, cmd, opt) |
|---|
| 478 | n/a | else: |
|---|
| 479 | n/a | self.sock.sendall(IAC + WONT + opt) |
|---|
| 480 | n/a | elif cmd in (WILL, WONT): |
|---|
| 481 | n/a | self.msg('IAC %s %d', |
|---|
| 482 | n/a | cmd == WILL and 'WILL' or 'WONT', ord(opt)) |
|---|
| 483 | n/a | if self.option_callback: |
|---|
| 484 | n/a | self.option_callback(self.sock, cmd, opt) |
|---|
| 485 | n/a | else: |
|---|
| 486 | n/a | self.sock.sendall(IAC + DONT + opt) |
|---|
| 487 | n/a | except EOFError: # raised by self.rawq_getchar() |
|---|
| 488 | n/a | self.iacseq = b'' # Reset on EOF |
|---|
| 489 | n/a | self.sb = 0 |
|---|
| 490 | n/a | pass |
|---|
| 491 | n/a | self.cookedq = self.cookedq + buf[0] |
|---|
| 492 | n/a | self.sbdataq = self.sbdataq + buf[1] |
|---|
| 493 | n/a | |
|---|
| 494 | n/a | def rawq_getchar(self): |
|---|
| 495 | n/a | """Get next char from raw queue. |
|---|
| 496 | n/a | |
|---|
| 497 | n/a | Block if no data is immediately available. Raise EOFError |
|---|
| 498 | n/a | when connection is closed. |
|---|
| 499 | n/a | |
|---|
| 500 | n/a | """ |
|---|
| 501 | n/a | if not self.rawq: |
|---|
| 502 | n/a | self.fill_rawq() |
|---|
| 503 | n/a | if self.eof: |
|---|
| 504 | n/a | raise EOFError |
|---|
| 505 | n/a | c = self.rawq[self.irawq:self.irawq+1] |
|---|
| 506 | n/a | self.irawq = self.irawq + 1 |
|---|
| 507 | n/a | if self.irawq >= len(self.rawq): |
|---|
| 508 | n/a | self.rawq = b'' |
|---|
| 509 | n/a | self.irawq = 0 |
|---|
| 510 | n/a | return c |
|---|
| 511 | n/a | |
|---|
| 512 | n/a | def fill_rawq(self): |
|---|
| 513 | n/a | """Fill raw queue from exactly one recv() system call. |
|---|
| 514 | n/a | |
|---|
| 515 | n/a | Block if no data is immediately available. Set self.eof when |
|---|
| 516 | n/a | connection is closed. |
|---|
| 517 | n/a | |
|---|
| 518 | n/a | """ |
|---|
| 519 | n/a | if self.irawq >= len(self.rawq): |
|---|
| 520 | n/a | self.rawq = b'' |
|---|
| 521 | n/a | self.irawq = 0 |
|---|
| 522 | n/a | # The buffer size should be fairly small so as to avoid quadratic |
|---|
| 523 | n/a | # behavior in process_rawq() above |
|---|
| 524 | n/a | buf = self.sock.recv(50) |
|---|
| 525 | n/a | self.msg("recv %r", buf) |
|---|
| 526 | n/a | self.eof = (not buf) |
|---|
| 527 | n/a | self.rawq = self.rawq + buf |
|---|
| 528 | n/a | |
|---|
| 529 | n/a | def sock_avail(self): |
|---|
| 530 | n/a | """Test whether data is available on the socket.""" |
|---|
| 531 | n/a | with _TelnetSelector() as selector: |
|---|
| 532 | n/a | selector.register(self, selectors.EVENT_READ) |
|---|
| 533 | n/a | return bool(selector.select(0)) |
|---|
| 534 | n/a | |
|---|
| 535 | n/a | def interact(self): |
|---|
| 536 | n/a | """Interaction function, emulates a very dumb telnet client.""" |
|---|
| 537 | n/a | if sys.platform == "win32": |
|---|
| 538 | n/a | self.mt_interact() |
|---|
| 539 | n/a | return |
|---|
| 540 | n/a | with _TelnetSelector() as selector: |
|---|
| 541 | n/a | selector.register(self, selectors.EVENT_READ) |
|---|
| 542 | n/a | selector.register(sys.stdin, selectors.EVENT_READ) |
|---|
| 543 | n/a | |
|---|
| 544 | n/a | while True: |
|---|
| 545 | n/a | for key, events in selector.select(): |
|---|
| 546 | n/a | if key.fileobj is self: |
|---|
| 547 | n/a | try: |
|---|
| 548 | n/a | text = self.read_eager() |
|---|
| 549 | n/a | except EOFError: |
|---|
| 550 | n/a | print('*** Connection closed by remote host ***') |
|---|
| 551 | n/a | return |
|---|
| 552 | n/a | if text: |
|---|
| 553 | n/a | sys.stdout.write(text.decode('ascii')) |
|---|
| 554 | n/a | sys.stdout.flush() |
|---|
| 555 | n/a | elif key.fileobj is sys.stdin: |
|---|
| 556 | n/a | line = sys.stdin.readline().encode('ascii') |
|---|
| 557 | n/a | if not line: |
|---|
| 558 | n/a | return |
|---|
| 559 | n/a | self.write(line) |
|---|
| 560 | n/a | |
|---|
| 561 | n/a | def mt_interact(self): |
|---|
| 562 | n/a | """Multithreaded version of interact().""" |
|---|
| 563 | n/a | import _thread |
|---|
| 564 | n/a | _thread.start_new_thread(self.listener, ()) |
|---|
| 565 | n/a | while 1: |
|---|
| 566 | n/a | line = sys.stdin.readline() |
|---|
| 567 | n/a | if not line: |
|---|
| 568 | n/a | break |
|---|
| 569 | n/a | self.write(line.encode('ascii')) |
|---|
| 570 | n/a | |
|---|
| 571 | n/a | def listener(self): |
|---|
| 572 | n/a | """Helper for mt_interact() -- this executes in the other thread.""" |
|---|
| 573 | n/a | while 1: |
|---|
| 574 | n/a | try: |
|---|
| 575 | n/a | data = self.read_eager() |
|---|
| 576 | n/a | except EOFError: |
|---|
| 577 | n/a | print('*** Connection closed by remote host ***') |
|---|
| 578 | n/a | return |
|---|
| 579 | n/a | if data: |
|---|
| 580 | n/a | sys.stdout.write(data.decode('ascii')) |
|---|
| 581 | n/a | else: |
|---|
| 582 | n/a | sys.stdout.flush() |
|---|
| 583 | n/a | |
|---|
| 584 | n/a | def expect(self, list, timeout=None): |
|---|
| 585 | n/a | """Read until one from a list of a regular expressions matches. |
|---|
| 586 | n/a | |
|---|
| 587 | n/a | The first argument is a list of regular expressions, either |
|---|
| 588 | n/a | compiled (re.RegexObject instances) or uncompiled (strings). |
|---|
| 589 | n/a | The optional second argument is a timeout, in seconds; default |
|---|
| 590 | n/a | is no timeout. |
|---|
| 591 | n/a | |
|---|
| 592 | n/a | Return a tuple of three items: the index in the list of the |
|---|
| 593 | n/a | first regular expression that matches; the match object |
|---|
| 594 | n/a | returned; and the text read up till and including the match. |
|---|
| 595 | n/a | |
|---|
| 596 | n/a | If EOF is read and no text was read, raise EOFError. |
|---|
| 597 | n/a | Otherwise, when nothing matches, return (-1, None, text) where |
|---|
| 598 | n/a | text is the text received so far (may be the empty string if a |
|---|
| 599 | n/a | timeout happened). |
|---|
| 600 | n/a | |
|---|
| 601 | n/a | If a regular expression ends with a greedy match (e.g. '.*') |
|---|
| 602 | n/a | or if more than one expression can match the same input, the |
|---|
| 603 | n/a | results are undeterministic, and may depend on the I/O timing. |
|---|
| 604 | n/a | |
|---|
| 605 | n/a | """ |
|---|
| 606 | n/a | re = None |
|---|
| 607 | n/a | list = list[:] |
|---|
| 608 | n/a | indices = range(len(list)) |
|---|
| 609 | n/a | for i in indices: |
|---|
| 610 | n/a | if not hasattr(list[i], "search"): |
|---|
| 611 | n/a | if not re: import re |
|---|
| 612 | n/a | list[i] = re.compile(list[i]) |
|---|
| 613 | n/a | if timeout is not None: |
|---|
| 614 | n/a | deadline = _time() + timeout |
|---|
| 615 | n/a | with _TelnetSelector() as selector: |
|---|
| 616 | n/a | selector.register(self, selectors.EVENT_READ) |
|---|
| 617 | n/a | while not self.eof: |
|---|
| 618 | n/a | self.process_rawq() |
|---|
| 619 | n/a | for i in indices: |
|---|
| 620 | n/a | m = list[i].search(self.cookedq) |
|---|
| 621 | n/a | if m: |
|---|
| 622 | n/a | e = m.end() |
|---|
| 623 | n/a | text = self.cookedq[:e] |
|---|
| 624 | n/a | self.cookedq = self.cookedq[e:] |
|---|
| 625 | n/a | return (i, m, text) |
|---|
| 626 | n/a | if timeout is not None: |
|---|
| 627 | n/a | ready = selector.select(timeout) |
|---|
| 628 | n/a | timeout = deadline - _time() |
|---|
| 629 | n/a | if not ready: |
|---|
| 630 | n/a | if timeout < 0: |
|---|
| 631 | n/a | break |
|---|
| 632 | n/a | else: |
|---|
| 633 | n/a | continue |
|---|
| 634 | n/a | self.fill_rawq() |
|---|
| 635 | n/a | text = self.read_very_lazy() |
|---|
| 636 | n/a | if not text and self.eof: |
|---|
| 637 | n/a | raise EOFError |
|---|
| 638 | n/a | return (-1, None, text) |
|---|
| 639 | n/a | |
|---|
| 640 | n/a | def __enter__(self): |
|---|
| 641 | n/a | return self |
|---|
| 642 | n/a | |
|---|
| 643 | n/a | def __exit__(self, type, value, traceback): |
|---|
| 644 | n/a | self.close() |
|---|
| 645 | n/a | |
|---|
| 646 | n/a | |
|---|
| 647 | n/a | def test(): |
|---|
| 648 | n/a | """Test program for telnetlib. |
|---|
| 649 | n/a | |
|---|
| 650 | n/a | Usage: python telnetlib.py [-d] ... [host [port]] |
|---|
| 651 | n/a | |
|---|
| 652 | n/a | Default host is localhost; default port is 23. |
|---|
| 653 | n/a | |
|---|
| 654 | n/a | """ |
|---|
| 655 | n/a | debuglevel = 0 |
|---|
| 656 | n/a | while sys.argv[1:] and sys.argv[1] == '-d': |
|---|
| 657 | n/a | debuglevel = debuglevel+1 |
|---|
| 658 | n/a | del sys.argv[1] |
|---|
| 659 | n/a | host = 'localhost' |
|---|
| 660 | n/a | if sys.argv[1:]: |
|---|
| 661 | n/a | host = sys.argv[1] |
|---|
| 662 | n/a | port = 0 |
|---|
| 663 | n/a | if sys.argv[2:]: |
|---|
| 664 | n/a | portstr = sys.argv[2] |
|---|
| 665 | n/a | try: |
|---|
| 666 | n/a | port = int(portstr) |
|---|
| 667 | n/a | except ValueError: |
|---|
| 668 | n/a | port = socket.getservbyname(portstr, 'tcp') |
|---|
| 669 | n/a | with Telnet() as tn: |
|---|
| 670 | n/a | tn.set_debuglevel(debuglevel) |
|---|
| 671 | n/a | tn.open(host, port, timeout=0.5) |
|---|
| 672 | n/a | tn.interact() |
|---|
| 673 | n/a | |
|---|
| 674 | n/a | if __name__ == '__main__': |
|---|
| 675 | n/a | test() |
|---|