1
2
3
4
5
6
7
8
9
10
11
12
13
14 __doc__="""TelnetSession
15
16 TelnetSession is used by TelnetSession to issue commands to a machine
17 and return their output over the telnet protocol.
18
19 Device Tree Parameters are:
20
21 zTelnetLoginTries - number of times to try login default: 1
22 zTelnetLoginTimeout - timeout for expect statements during login default: 2
23 zTelnetPromptTimeout - pause used during prompt discovery default: 0.2
24 zTelnetCommandTimeout - default timeout when executing a command default: 5
25 zTelnetLoginRegex - regex to match the login prompt default: 'ogin:.$'
26 zTelnetPasswordRegex - regext to match the password prompt default: 'assword:.$'
27
28 Other Parameters that are used by both TelnetSession and SshTransport:
29 zCommandPathList - list of path to check for a command
30 zCommandExistanceCheck - shell command issued to look for executible
31 must echo succ if executible is found
32 default: test -f executible
33
34 $Id: TelnetClient.py,v 1.15 2004/04/05 02:05:30 edahl Exp $"""
35
36 __version__ = "$Revision: 1.15 $"[11:-2]
37
38 import Globals
39
40
41 try:
42 from twisted.conch import telnet
43 except:
44 from twisted.protocols import telnet
45
46 from twisted.internet import protocol, reactor
47
48 import re
49 import logging
50 log = logging.getLogger("zen.TelnetClient")
51
52 import CollectorClient
53 from Exceptions import *
54
55 defaultPromptTimeout = 10
56 defaultCommandTimeout = 20
57 defaultLoginRegex = 'ogin:.$'
58 defaultPasswordRegex = 'assword:'
59 defaultEnable = False
60 defaultTermLength = False
61
62
63 responceMap = ("WILL", "WONT", "DO", "DONT")
64
66 "check to see if a device supports telnet"
67 from telnetlib import Telnet
68 import socket
69 try:
70 tn = Telnet(hostname)
71 tn.close()
72 return 1
73 except socket.error:
74 return 0
75
76
78 mode = 'Login'
79
80 timeout = 0
81 timeoutID = None
82 p1 = ""
83 p2 = ""
84 commandPrompt = ""
85 command = ''
86 enabled = -1
87 scCallLater = None
88 bytes = ''
89 lastwrite = ''
90 result = ''
91 buffer = ""
92
99
100
102 log.debug("received telnet DO feature %s" % ord(feature))
103 if ord(feature) == 1:
104 self._iac_responce(telnet.WILL, feature)
105 else:
106 self._iac_responce(telnet.WONT, feature)
107
109 log.debug("received telnet DONT feature %s" % ord(feature))
110 self._iac_responce(telnet.WONT, feature)
111
113 log.debug("received telnet WILL feature %s" % ord(feature))
114 self._iac_responce(telnet.DONT, feature)
115
117 log.debug("received telnet WONT feature %s" % ord(feature))
118 self._iac_responce(telnet.DONT, feature)
119
124
125
130
141
143 """I call a method that looks like 'telnet_*' where '*' is filled
144 in by the current mode. telnet_* methods should return a string which
145 will become the new mode."""
146 line = re.sub("\r\n|\r", "\n", line)
147
148 if self.lastwrite.startswith(line):
149 self.lastwrite = self.lastwrite[len(line):]
150 line = ''
151 elif line.find(self.lastwrite) == 0:
152 line = line[len(self.lastwrite):]
153 log.debug("mode = %s", self.mode)
154 self.mode = getattr(self, "telnet_"+self.mode)(line)
155
162
165
166
171
172
176
177
186
187
188
200
201
217
218
227
228
234
235
260
265
275
276
298
299
302
303
305
306 - def __init__(self, hostname, ip, port, commands=[], options=None,
307 device=None, datacollector=None):
308 CollectorClient.CollectorClient.__init__(self, hostname, ip, port,
309 commands, options, device, datacollector)
310 self.protocol = TelnetClientProtocol
311 self.modeRegex = {
312 'FindPrompt' : '.*',
313 'WasteTime' : '.*',
314 'Done' : '',
315 }
316 self.promptPause = 1
317
318 if options:
319 defaultPromptTimeout = options.promptTimeout
320 defaultCommandTimeout = options.commandTimeout
321 defaultLoginRegex = options.loginRegex
322 defaultPasswordRegex = options.passwordRegex
323 defaultEnable = options.enable
324 defaultTermLength = options.termlen
325
326 if device:
327 self.promptTimeout = getattr(device,
328 'zTelnetPromptTimeout', defaultPromptTimeout)
329 self.loginRegex = getattr(device,
330 'zTelnetLoginRegex', defaultLoginRegex)
331 self.passwordRegex = getattr(device,
332 'zTelnetPasswordRegex', defaultPasswordRegex)
333 self.enable = getattr(device,
334 'zTelnetEnable', defaultEnable)
335 self.termlen = getattr(device,
336 'zTelnetTermLength', defaultTermLength)
337 else:
338 self.promptTimeout = defaultPromptTimeout
339 self.loginRegex = defaultLoginRegex
340 self.passwordRegex = defaultPasswordRegex
341 self.enable = defaultEnable
342 self.termlen = defaultTermLength
343
344 self.modeRegex['Login'] = self.loginRegex
345 self.modeRegex['Password'] = self.passwordRegex
346
347
349 """Start telnet collection.
350 """
351 if self.termlen:
352 self._commands.insert(0, "terminal length 0")
353 reactor.connectTCP(self.ip, self.port, self)
354
355
361
362
364 """if we don't connect let the modeler know"""
365 log.warn(reason.getErrorMessage())
366 self.clientFinished()
367
368
373
374
376 parser = CollectorClient.buildOptions(parser,usage)
377 parser.add_option('-r', '--promptTimeout',
378 dest='promptTimeout',
379 type = 'float',
380 default = defaultPromptTimeout,
381 help='timeout when discovering prompt')
382 parser.add_option('-x', '--loginRegex',
383 dest='loginRegex',
384 default = defaultLoginRegex,
385 help='regex that will find the login prompt')
386 parser.add_option('-w', '--passwordRegex',
387 dest='passwordRegex',
388 default = defaultPasswordRegex,
389 help='regex that will find the password prompt')
390 parser.add_option('--enable',
391 dest='enable', action='store_true', default=False,
392 help='enter enable mode on a cisco device')
393 parser.add_option('--termlen',
394 dest='termlen', action='store_true', default=False,
395 help='enter send terminal length 0 on a cisco device')
396 return parser
397
398
400 import socket
401 import getpass
402 parser = buildOptions()
403 options = CollectorClient.parseOptions(parser, 23)
404 if not options.password:
405 options.password = getpass.getpass("%s@%s's password: " %
406 (options.username, options.hostname))
407 logging.basicConfig(level=10)
408 commands = [("test", c) for c in options.commands]
409 client = TelnetClient(options.hostname,
410 socket.gethostbyname(options.hostname),
411 options.port,
412 commands=commands, options=options)
413 client.run()
414 def stop():
415 if client.commandsFinished():
416 reactor.stop()
417 else:
418 reactor.callLater(1, stop)
419 stop()
420 reactor.run()
421 import pprint
422 pprint.pprint(client.getResults())
423
424 if __name__ == '__main__':
425 main()
426