码迷,mamicode.com
首页 > 其他好文 > 详细

SSHClient

时间:2020-08-06 00:55:54      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:osi   arch   gen   lock   support   ror   led   miss   ted   

  1 import os
  2 import re
  3 import sys
  4 import time
  5 import traceback
  6 import paramiko
  7 import telnetlib
  8 from functools import reduce
  9 from pprint import pprint
 10 from .MyPrint import MyPrint
 11 from .PathConfig import pathOutcome
 12 
 13 
 14 #=========================================================
 15 
 16 class Pattern(object):
 17     #------------------------------------------------
 18     neFlag              = re.compile(r^([<\[])?([^#<>\[\]\s]+)(?(1)[>\]]\s*$|#\s*$))
 19     #                                    \---/   \-----------/   \-/ \-------/ \---/
 20     #                                      |           |          |      |       |
 21     #                                      |           |          |      |    CISCO device
 22     #                                HUAWEI device     |          |  HUAWEI device
 23     #                                                  |   IF HUAWEI device
 24     #                                              device name
 25     nebyteFlag          = re.compile(rb([<\[])?([^#<>\[\]\s]+)(?(1)[>\]]\s*$|#\s*$))
 26     #------------------------------------------------
 27     linuxFlag           = re.compile(r^([^#\$]+)[#\$]\s*$)
 28     linuxbyteFlag       = re.compile(rb^([^#\$]+)[#\$]\s*$)
 29     #------------------------------------------------
 30     moreFlag            = re.compile(r-.*more.*-, re.I)
 31     morebyteFlag        = re.compile(rb-.*more.*-,re.I)
 32     #------------------------------------------------
 33     continueFlag        = re.compile(rPress any key to continue \(Q to quit\))
 34     continuebyteFlag    = re.compile(rbPress any key to continue \(Q to quit\))
 35 
 36     #------------------------------------------------
 37     loginFlag           = re.compile(r(?:login|username):, re.I)
 38     loginbyteFlag       = re.compile(rb(?:login|username):, re.I)
 39 
 40     #------------------------------------------------
 41     passordFlag         = re.compile(rpassword:, re.I)
 42     passordbyteFlag     = re.compile(rbpassword:, re.I)
 43     #------------------------------------------------
 44     pwdChangeFlag       = re.compile(
 45                             rThe password needs to be changed\. Change now\? \[Y/N\]:
 46                         )
 47     pwdChangebyteFlag   = re.compile(
 48                             rbThe password needs to be changed\. Change now\? \[Y/N\]:
 49                         )
 50     #------------------------------------------------
 51     firstSshFlag        = re.compile(
 52                             rAre you sure you want to continue connecting \(yes/no\)\?
 53                         )
 54     #------------------------------------------------
 55     yes_no_Flag         = re.compile(r\(yes/no\))
 56     yes_no_byteFlag     = re.compile(rb\(yes/no\))
 57     #------------------------------------------------
 58     Y_N_Flag            = re.compile(r\[Y/N\])
 59     Y_N_byteFlag        = re.compile(rb\[Y/N\])
 60     #------------------------------------------------
 61     Y_N_C_Flag          = re.compile(r\[Y\(yes\)/N\(no\)/C\(cancel\)\]:)
 62     Y_N_C_byteFlag      = re.compile(rb\[Y\(yes\)/N\(no\)/C\(cancel\)\]:)
 63     #------------------------------------------------
 64     neErrorFlag         = re.compile(
 65                             r"Error: (?:(?:Incomplete|Unrecognized) command found at ‘\^‘ position\.|"
 66                             r"The specified \S+ does not exist\.|"
 67                             r"The command must be executed singly, "
 68                             r"please commit uncommitted configuration first|"
 69                             r"Bad command\.|Invalid parameter\.)?"
 70                         )
 71     neErrorbyteFlag     = re.compile(
 72                             rb"Error: (?:(?:Incomplete|Unrecognized) command found at ‘\^‘ position\.|"
 73                             rb"The specified \S+ does not exist\.|"
 74                             rb"The command must be executed singly, "
 75                             rb"please commit uncommitted configuration first|"
 76                             rb"Bad command\.|Invalid parameter\.)?"
 77                         )
 78     neWarningFlag       = re.compile(
 79                             rWarning: (?:The current configuration will be written to the device\.)?
 80                         )
 81     neWarningbyteFlag   = re.compile(
 82                             rbWarning: (?:The current configuration will be written to the device\.)?
 83                         )
 84     #------------------------------------------------
 85     sshFlag             = re.compile(rssh \S+@(\d{1,3}(?:\.\d{1,3}){3}))
 86     sshbyteFlag         = re.compile(rbssh \S+@(\d{1,3}(?:\.\d{1,3}){3}))
 87 
 88 
 89     sshErrorFlag        = re.compile(
 90                             r(?:ssh: connect to host \d{1,3}(?:\.\d{1,3}){3} port 22: 
 91                             r(?:Connection timed out|Resource temporarily unavailable)|
 92                             rssh_exchange_identification: Connection closed by remote host|
 93                             rThe user has been locked and you cannot log on it\.|
 94                             rReceived disconnect from \d{1,3}(?:\.\d{1,3}){3} 
 95                             rport 22:2: The connection is closed by SSH Server|
 96                             rDisconnected from \d{1,3}(?:\.\d{1,3}){3} port 22)
 97                         )
 98 
 99     sshErrorbyteFlag    = re.compile(
100                             rb(?:ssh: connect to host \d{1,3}(?:\.\d{1,3}){3} port 22: 
101                             rb(?:Connection timed out|Resource temporarily unavailable)|
102                             rbssh_exchange_identification: Connection closed by remote host|
103                             rbThe user has been locked and you cannot log on it\.|
104                             rbReceived disconnect from \d{1,3}(?:\.\d{1,3}){3} 
105                             rbport 22:2: The connection is closed by SSH Server|
106                             rbDisconnected from \d{1,3}(?:\.\d{1,3}){3} port 22)
107                         )
108 #=========================================================
109 
110 class ConnectError(Exception):
111     pass
112 
113 
114 class NeError(Exception):
115     pass
116 
117 
118 class SSH_Client(object):
119     def __init__(self, address, username, password, port=22):
120         self._ip = address
121         self._client = paramiko.SSHClient()
122         self._client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
123         self._client.connect(
124             hostname=address, 
125             username=username, 
126             password=password,
127             port=port, 
128             timeout=20, 
129             banner_timeout=20, 
130             look_for_keys=False, 
131             allow_agent=False
132         )
133         self._shell = self._client.invoke_shell()
134 
135     def bufferReady(self, interval=0.1):
136         while True:
137             time.sleep(interval)
138             if self._shell.recv_ready() or self._shell.recv_stderr_ready():
139                 break
140 
141     def recv_unit(self, interval):
142         temp = ‘‘
143         endMark = 0
144         while True:
145             if (Pattern.neFlag.match(temp.split(\n)[-1].strip()) 
146                 or Pattern.linuxFlag.match(temp.split(\n)[-1].strip())
147                 or Pattern.loginFlag.search(temp.split(\n)[-1]) 
148                 or Pattern.passordFlag.search(temp.split(\n)[-1])
149                 or Pattern.pwdChangeFlag.search(temp.split(\n)[-1])
150                 or Pattern.firstSshFlag.search(temp.split(\n)[-1])
151                 or Pattern.yes_no_Flag.search(temp.split(\n)[-1]) 
152                 or Pattern.Y_N_Flag.search(temp.split(\n)[-1]) 
153                 or Pattern.Y_N_C_Flag.search(temp.split(\n)[-1])
154                 or Pattern.moreFlag.search(temp.split(\n)[-1]) 
155                 or Pattern.continueFlag.search(temp.split(\n)[-1])
156                 ):
157                 #print(‘WWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWWW‘)
158                 endMark = 1
159                 break
160             elif temp.endswith(\r\n) and len(temp) > 300:
161                 #print(‘QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ‘)
162                 endMark = 2
163                 break
164             #-----------------------------
165             elif len(temp) > 99999:
166                 #print(‘RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR‘)
167                 endMark = 3
168                 break
169             #-----------------------------
170             self.bufferReady(interval)
171             temp += self._shell.recv(99999).decode(encoding=UTF-8, errors=replace)
172 
173         return temp, endMark
174 
175     def recv_all(self, deviceMark, cmdBefore, cmdAfter, interval=0.1):
176         output = ‘‘
177         #self.bufferReady(interval)
178         #temp = self._shell.recv(99999).decode(encoding=‘UTF-8‘, errors=‘replace‘)
179         temp, endMark = self.recv_unit(interval)
180         output += temp
181         #------------------------------------
182         if (Pattern.neFlag.match(deviceMark.strip()) 
183             or Pattern.linuxFlag.match(deviceMark.strip())
184             ):
185             if Pattern.neErrorFlag.search(temp):
186                 #--------------
187                 #MyPrint.Blue(‘++++++++++++++++++++‘)
188                 #print(deviceMark, ‘=====> ‘, temp.split(‘\n‘)[0])
189                 #pprint(temp)
190                 #MyPrint.Blue(‘====================‘)
191                 #--------------
192                 MyPrint.Red(deviceMark.strip() + temp.split(\n)[0].strip())
193                 #raise NeError(‘Command Error‘)
194             elif Pattern.neWarningFlag.search(temp):
195                 #--------------
196                 #MyPrint.Blue(‘++++++++++++++++++++‘)
197                 #print(deviceMark, ‘=====> ‘, temp.split(‘\n‘)[0])
198                 #pprint(temp)
199                 #MyPrint.Blue(‘====================‘)
200                 #--------------
201                 MyPrint.Yellow(deviceMark.strip() + temp.split(\n)[0].strip())
202             else:
203                 #--------------
204                 #MyPrint.Blue(‘++++++++++++++++++++‘)
205                 #print(deviceMark, ‘=====> ‘, temp.split(‘\n‘)[0])
206                 #pprint(temp)
207                 #MyPrint.Blue(‘====================‘)
208                 #--------------
209                 MyPrint.Green(deviceMark.strip() + temp.split(\n)[0].strip())
210         #elif (Pattern.yes_no_Flag.search(deviceMark) 
211         #        or Pattern.Y_N_Flag.search(deviceMark) 
212         #        or Pattern.Y_N_C_Flag.search(deviceMark)
213         #    ):
214         #    print(deviceMark.strip() + temp.split(‘\n‘)[0].strip())
215         else:
216             #--------------
217             MyPrint.Blue(++++++++++++++++++++)
218             print(deviceMark, =====> , temp.split(\n)[0])
219             pprint(temp)
220             MyPrint.Blue(====================)
221             #--------------
222             print(deviceMark.strip() + temp.split(\n)[0].strip())
223 
224         if endMark == 1:
225             for line in temp.split(\n)[1:-1]:
226                 if line and line != \r:
227                     #print(line, flush=True)
228                     print(line)
229             #if temp.split(‘\n‘)[1:-1]:
230             #    print(reduce(lambda x, y: x + ‘\n‘ + y, temp.split(‘\n‘)[1:-1]).strip())
231         else:
232             for line in temp.split(\n)[1:]:
233                 if line and line != \r:
234                     #print(line, flush=True)
235                     print(line)
236             #if temp.split(‘\n‘)[1:]:
237             #    print(reduce(lambda x, y: x + ‘\n‘ + y, temp.split(‘\n‘)[1:]).strip())
238         #------------------------------------
239         while True:
240             #==============================================================
241             if (Pattern.neFlag.match(temp.split(\n)[-1].strip()) 
242                 or Pattern.linuxFlag.match(temp.split(\n)[-1].strip())
243                 ):
244                 deviceMark = temp.split(\n)[-1]
245                 if len(temp.split(\n)) >= 2 and Pattern.sshErrorFlag.search(temp.split(\n)[-2]):
246                     raise ConnectError(Connection failed)
247                 break
248             #==============================================================
249             elif (Pattern.loginFlag.search(temp.split(\n)[-1])
250                 or Pattern.passordFlag.search(temp.split(\n)[-1])
251                 ):
252                 deviceMark = temp.split(\n)[-1]
253                 if len(temp.split(\n)) >= 2 and Pattern.sshErrorFlag.search(temp.split(\n)[-2]):
254                     raise ConnectError(Connection failed)
255                 break
256             #==============================================================
257             elif Pattern.pwdChangeFlag.search(temp.split(\n)[-1]):
258                 deviceMark = temp.split(\n)[-1]
259                 #print(deviceMark + ‘N‘)
260                 self._shell.send(N\n)
261                 deviceMark, temp = self.recv_all(deviceMark, cmdBefore, cmdAfter, interval)
262                 output += temp
263                 break
264             elif Pattern.firstSshFlag.search(temp.split(\n)[-1]):
265                 deviceMark = temp.split(\n)[-1]
266                 self._shell.send(yes\n)
267                 deviceMark, temp = self.recv_all(deviceMark, cmdBefore, cmdAfter, interval)
268                 output += temp
269                 break
270             #==============================================================
271             elif (Pattern.yes_no_Flag.search(temp.split(\n)[-1]) 
272                 or Pattern.Y_N_Flag.search(temp.split(\n)[-1]) 
273                 or Pattern.Y_N_C_Flag.search(temp.split(\n)[-1])
274                 ):
275                 if cmdAfter not in (Y, y, N, n, C, c, yes, no, cancel):
276                     deviceMark = temp.split(\n)[-1]
277                     yourChoice = ‘‘
278                     while True:
279                         yourChoice = input(temp.split(\n)[-1])
280                         if yourChoice in (Y, y, N, n, C, c, yes, no, cancel):
281                             break
282                     self._shell.send(yourChoice + \n)
283                     deviceMark, temp = self.recv_all(deviceMark, cmdBefore, cmdAfter, interval)
284                     output += temp
285                 else:
286                     deviceMark = temp.split(\n)[-1]
287                 break
288             #==============================================================
289             elif (Pattern.moreFlag.search(temp.split(\n)[-1]) 
290                 or Pattern.continueFlag.search(temp.split(\n)[-1])
291                 ):
292                 deviceMark = temp.split(\n)[-1]
293                 self._shell.send( )
294                 deviceMark, temp = self.recv_all(deviceMark, cmdBefore, cmdAfter, interval)
295                 output += temp
296                 break
297             #==============================================================
298             #self.bufferReady(interval)
299             #temp = self._shell.recv(99999).decode(encoding=‘UTF-8‘, errors=‘replace‘)
300             temp, endMark = self.recv_unit(interval)
301             output += temp
302             #----------------------------
303             #MyPrint.Yellow(‘++++++++++++++++‘)
304             #pprint(temp)
305             #MyPrint.Yellow(‘================‘)
306             #----------------------------
307             #------------------------------------
308             if endMark == 1:
309                 for line in temp.split(\n)[:-1]:
310                     if line and line != \r:
311                         #print(line.strip(‘\r‘), flush=True)
312                         #print(line, flush=True)
313                         print(line)
314                 #if temp.split(‘\n‘)[:-1]:
315                 #    print(reduce(lambda x, y: x + ‘\n‘ + y, temp.split(‘\n‘)[:-1]).strip())
316             else:
317                 for line in temp.split(\n):
318                     if line and line != \r:
319                         #print(line.strip(‘\r‘), flush=True)
320                         #print(line, flush=True)
321                         print(line)
322                 #if temp.split(‘\n‘):
323                 #    print(reduce(lambda x, y: x + ‘\n‘ + y, temp.split(‘\n‘)).strip())
324             #------------------------------------
325             #==============================================================
326         return deviceMark, output
327 
328     def send_command(self, command, deviceMark, cmdBefore, cmdAfter, interval=0.1):
329         if command.endswith(\n):
330             pass
331         else:
332             command += \n
333         self._shell.send(command)
334         deviceMark, stdout = self.recv_all(deviceMark, cmdBefore, cmdAfter, interval)
335         return deviceMark, stdout
336 
337     def run(self, cmds, interval=0.1):
338         res, stdout, deviceMark = Below commands may be wrong:\n, ‘‘, ‘‘
339         #====================================================================
340         #self.bufferReady(interval)
341         #temp = self._shell.recv(99999).decode(encoding=‘UTF-8‘, errors=‘replace‘)
342         temp, endMark = self.recv_unit(interval)
343         stdout += temp
344         while True:
345             if (Pattern.neFlag.match(temp.split(\n)[-1].strip()) 
346                 or Pattern.linuxFlag.match(temp.split(\n)[-1].strip())):
347                 deviceMark = temp.split(\n)[-1]
348                 break
349             elif Pattern.pwdChangeFlag.search(temp.split(\n)[-1]):
350                 self._shell.send(N\n)
351             #self.bufferReady(interval)
352             #temp = self._shell.recv(99999).decode(encoding=‘UTF-8‘, errors=‘replace‘)
353             temp, endMark = self.recv_unit(interval)
354             stdout += temp
355         #====================================================================
356         if deviceMark:
357             cmdList = cmds.split(\n)
358             for index, cmd in enumerate(cmdList):
359                 if cmd.strip():
360                     cmdBefore, cmdAfter = ‘‘, ‘‘
361                     try:
362                         cmdBefore = cmdList[index - 1].strip()
363                         cmdAfter = cmdList[index + 1].strip()
364                     except IndexError:
365                         pass
366                     deviceMark, stdout_temp = self.send_command(
367                         cmd, deviceMark, cmdBefore, cmdAfter, interval
368                     )
369                     stdout += stdout_temp
370                     if Pattern.neErrorFlag.search(stdout_temp):
371                         res += (cmd + \n)
372             if res == Below commands may be wrong:\n:
373                 res = All commands are executed perfectly
374             else:
375                 res = res.strip() + $%^&
376         return res, stdout
377 
378     def close(self):
379         self._client.close()
380 
381 
382 class Telnet_Client(object):
383     def __init__(self, address, username, password, port=23):
384         self._telnet = telnetlib.Telnet()
385         self._telnet.open(address=address, port=port)
386         self._telnet.read_until(b:, timeout=5)
387         self._telnet.write(username.encode(ascii) + b\n)
388         self._telnet.read_until(bassword:, timeout=5)
389         self._telnet.write(password.encode(ascii) + b\n)
390         time.sleep(2)
391         self._telnet.read_very_eager().decode(encoding=UTF-8, errors=replace)
392 
393     def send_command(self, command, interval):
394         self._telnet.write(command.encode(ascii) + b\n)
395         stdout = self._telnet.expect(
396             [
397                 Pattern.nebyteFlag, 
398                 Pattern.linuxbyteFlag, 
399                 Pattern.pwdChangebyteFlag, 
400                 Pattern.morebyteFlag, 
401                 Pattern.continuebyteFlag, 
402                 Pattern.loginbyteFlag, 
403                 Pattern.passordbyteFlag
404             ], 
405             timeout=interval
406         )[2].decode(encoding=UTF-8, errors=replace)
407         data = stdout.split(\n)
408         while (Pattern.moreFlag.search(data[-1]) or Pattern.continuebyteFlag.search(data[-1])):
409             self._telnet.write(b )
410             #tmp = self._telnet.read_very_eager().decode(encoding=‘UTF-8‘, errors=‘replace‘)
411             tmp = self._telnet.expect(
412                 [
413                     Pattern.nebyteFlag, 
414                     Pattern.linuxbyteFlag, 
415                     Pattern.pwdChangebyteFlag, 
416                     Pattern.morebyteFlag, 
417                     Pattern.continuebyteFlag, 
418                     Pattern.loginbyteFlag, 
419                     Pattern.passordbyteFlag
420                 ], 
421                 timeout=interval
422             )[2].decode(encoding=UTF-8, errors=replace)
423             #time.sleep(0.5)
424             data = tmp.split(\n)
425             stdout += tmp
426         return stdout
427 
428     def run(self, cmds, interval):
429         res, stdout = Below commands may be wrong:\n, ‘‘
430         stdout += self.send_command( , interval)
431         print(stdout)
432         for cmd in cmds.split(\n):
433             if cmd.strip():
434                 stdout_temp = self.send_command(cmd, interval)
435                 stdout += stdout_temp
436                 for line in stdout_temp.split(\n):
437                     print(line)
438 
439                 if Pattern.neErrorFlag.search(stdout_temp):
440                     res += (cmd + \n)
441 
442         if res == Below commands may be wrong:\n:
443             res = All commands are executed perfectly
444         else:
445             res = res.strip() + $%^&
446         return res, stdout
447 
448     def close(self):
449         self._telnet.write(bexit\n)
450 
451 
452 class Actuator(object):
453     def __init__(self, config):
454         self._actuator = None
455         self.DestinationIP = config[DestinationIP]
456 
457         if config[Jumper1_IP] is None:
458             self._ip       = config[DestinationIP]
459             self._username = config[UserName]
460             self._password = config[Password]
461             self._method   = config[Method]
462             self._commands = config[Commands]
463             self._outcome  = [self._ip]
464         elif config[Jumper1_IP] is not None:
465             self._ip       = config[Jumper1_IP]
466             self._username = config[Jumper1_UserName]
467             self._password = config[Jumper1_Password]
468             self._method   = config[Jumper1_Method]
469 
470             if config[Jumper2_IP] is None:
471                 if config[Method] == SSH:
472                     self._commands = ssh {}@{}\n.format(
473                         config[UserName], config[DestinationIP]
474                     )
475                     self._commands += {}\n.format(config[Password])
476                     self._commands += config[Commands]
477                 elif config[Method] == Telnet:
478                     self._commands = telnet {}\n.format(config[DestinationIP])
479                     self._commands += {}\n.format(config[UserName])
480                     self._commands += {}\n.format(config[Password])
481                     self._commands += config[Commands]
482 
483             elif config[Jumper2_IP] is not None:
484                 if config[Jumper3_IP] is None:
485                     if config[Jumper2_Method] == SSH:
486                         self._commands = ssh {}@{}\n.format(
487                             config[Jumper2_UserName], config[Jumper2_IP]
488                         )
489                         self._commands += {}\n.format(config[Jumper2_Password])
490                     elif config[Jumper2_Method] == Telnet:
491                         self._commands = telnet {}\n.format(config[Jumper2_IP])
492                         self._commands += {}\n.format(config[Jumper2_UserName])
493                         self._commands += {}\n.format(config[Jumper2_Password])
494 
495                     if config[Method] == SSH:
496                         self._commands += ssh {}@{}\n.format(
497                             config[UserName], config[DestinationIP]
498                         )
499                         self._commands += {}\n.format(config[Password])
500                         self._commands += config[Commands]
501                     elif config[Method] == Telnet:
502                         self._commands += telnet {}\n.format(config[DestinationIP])
503                         self._commands += {}\n.format(config[UserName])
504                         self._commands += {}\n.format(config[Password])
505                         self._commands += config[Commands]
506                 else:
507                     if config[Jumper2_Method] == SSH:
508                         self._commands = ssh {}@{}\n.format(
509                             config[Jumper2_UserName], config[Jumper2_IP]
510                         )
511                         self._commands += {}\n.format(config[Jumper2_Password])
512                     elif config[Jumper2_Method] == Telnet:
513                         self._commands = telnet {}\n.format(config[Jumper2_IP])
514                         self._commands += {}\n.format(config[Jumper2_UserName])
515                         self._commands += {}\n.format(config[Jumper2_Password])
516 
517                     if config[Jumper3_Method] == SSH:
518                         self._commands += ssh {}@{}\n.format(
519                             config[Jumper3_UserName], config[Jumper3_IP]
520                         )
521                         self._commands += {}\n.format(config[Jumper3_Password])
522                     elif config[Jumper3_Method] == Telnet:
523                         self._commands += telnet {}\n.format(config[Jumper3_IP])
524                         self._commands += {}\n.format(config[Jumper3_UserName])
525                         self._commands += {}\n.format(config[Jumper3_Password])
526 
527                     if config[Method] == SSH:
528                         self._commands += ssh {}@{}\n.format(
529                             config[UserName], config[DestinationIP]
530                         )
531                         self._commands += {}\n.format(config[Password])
532                         self._commands += config[Commands]
533                     elif config[Method] == Telnet:
534                         self._commands += telnet {}\n.format(config[DestinationIP])
535                         self._commands += {}\n.format(config[UserName])
536                         self._commands += {}\n.format(config[Password])
537                         self._commands += config[Commands]
538             
539             self._outcome  = [config[DestinationIP]]
540             #print(self._commands)
541 
542     def __enter__(self):
543         MyPrint.Blue(
544             -------------------------------\n +
545             Connecting to {}\n.format(self.DestinationIP) + 
546             -------------------------------
547         )
548         try:
549             if self._method == SSH:
550                 self._actuator = SSH_Client(self._ip, self._username, self._password)
551             elif self._method == Telnet:
552                 self._actuator = Telnet_Client(self._ip, self._username, self._password)
553             MyPrint.Blue(
554                 -------------------------------\n +
555                 Connection to {} succeed\n.format(self.DestinationIP) + 
556                 -------------------------------
557             )
558         except:
559             self._actuator = None
560             MyPrint.Blue(
561                 -------------------------------\n +
562                 Connection to {} failed\n.format(self.DestinationIP) + 
563                 -------------------------------
564             )
565         return self
566 
567     def writeFile(self, stdout):
568         file_time = time.strftime(_%Y-%m-%d-%H-%M-%S, time.localtime())
569         file_name = os.path.join(pathOutcome, self.DestinationIP + file_time + .txt)
570         with open(file_name, w, encoding=utf-8) as f:
571             #-------------------------------------------------
572             f.write(
573                 # * 90 + \n + # +   * 88 + # + \n + # +   * 11 + 
574                 ^_^    A CLI Tool Made By Kelvin, Thanks For Your Support~~    ^_^ + 
575                   * 11 + # + \n + # +   * 88 + # + \n + # * 90 + \n
576             )
577             #-------------------------------------------------
578             for line in stdout.split(\r\n):
579                 f.write(line)
580                 f.write(\n)
581         #return file_name
582 
583     def runCommands(self):
584         interval = 0.01 if self._method == SSH else 5
585         if self._actuator:
586             try:
587                 res, stdout = self._actuator.run(self._commands, interval)
588             except ConnectError as e:
589                 self._outcome.extend([cannot be connected...@#$%, 0])
590             except:
591                 print(traceback.format_exc())
592             else:
593                 self.writeFile(stdout)
594                 self._outcome.extend([res, len(stdout.split(\r\n))])
595         else:   
596             self._outcome.extend([cannot be connected...@#$%, 0])
597 
598     def connectOutcome(self):
599         return self._outcome
600 
601     def __exit__(self, exc_ty, exc_val, tb):
602         time.sleep(5) if self._method == SSH else time.sleep(20)
603         if self._actuator is not None:
604             self._actuator.close()
605             self._actuator = None
606             MyPrint.Blue(
607                 -------------------------------\n +
608                 Connection closed\n + 
609                 -------------------------------
610             )

 

SSHClient

标签:osi   arch   gen   lock   support   ror   led   miss   ted   

原文地址:https://www.cnblogs.com/kHrystal/p/13443461.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!