Peter D Phan | e732f77 | 2021-07-01 10:16:35 -0500 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | import socket |
| 4 | import telnetlib |
| 5 | from collections import deque |
| 6 | |
| 7 | |
| 8 | class TelnetRemoteclient: |
| 9 | |
| 10 | r""" |
| 11 | Class to create telnet connection to remote host for command execution. |
| 12 | """ |
| 13 | |
| 14 | def __init__(self, hostname, username, password, port=23, read_timeout=None): |
| 15 | |
| 16 | r""" |
| 17 | Description of argument(s): |
| 18 | |
| 19 | hostname Name/IP of the remote (targeting) host |
| 20 | username User on the remote host with access to FFCD files |
| 21 | password Password for user on remote host |
| 22 | read_timeout New read timeout value to override default one |
| 23 | """ |
| 24 | |
| 25 | self.hostname = hostname |
| 26 | self.username = username |
| 27 | self.password = password |
| 28 | self.tnclient = None |
| 29 | self.port = port |
| 30 | self.read_timeout = read_timeout |
| 31 | |
| 32 | def tn_remoteclient_login(self): |
| 33 | |
| 34 | is_telnet = True |
| 35 | try: |
| 36 | self.tnclient = telnetlib.Telnet(self.hostname, self.port, timeout=15) |
| 37 | if b'login:' in self.tnclient.read_until(b'login:', timeout=self.read_timeout): |
| 38 | self.tnclient.write(self.username.encode('utf-8') + b"\n") |
| 39 | |
| 40 | if b'Password:' in self.tnclient.read_until(b'Password:', timeout=self.read_timeout): |
| 41 | self.tnclient.write(self.password.encode('utf-8') + b"\n") |
| 42 | |
| 43 | n, match, pre_match = \ |
| 44 | self.tnclient.expect( |
| 45 | [b'Login incorrect', b'invalid login name or password.', br'\#', br'\$'], |
| 46 | timeout=self.read_timeout) |
| 47 | if n == 0 or n == 1: |
| 48 | print("\n>>>>>\tERROR: Telnet Authentication Failed. Check userid and password.\n\n") |
| 49 | is_telnet = False |
| 50 | else: |
| 51 | # login successful |
| 52 | self.fifo = deque() |
| 53 | else: |
| 54 | # Anything else, telnet server is not running |
| 55 | print("\n>>>>>\tERROR: Telnet Connection Refused.\n\n") |
| 56 | is_telnet = False |
| 57 | else: |
| 58 | is_telnet = False |
| 59 | except Exception: |
| 60 | # Any kind of exception, skip telnet protocol |
| 61 | is_telnet = False |
| 62 | |
| 63 | return is_telnet |
| 64 | |
| 65 | def __del__(self): |
| 66 | self.tn_remoteclient_disconnect() |
| 67 | |
| 68 | def tn_remoteclient_disconnect(self): |
| 69 | try: |
| 70 | self.tnclient.close() |
| 71 | except Exception: |
| 72 | # the telnet object might not exist yet, so ignore this one |
| 73 | pass |
| 74 | |
| 75 | def execute_command(self, cmd, |
| 76 | rtnpartial=False, |
| 77 | wait_cnt=5, |
| 78 | i_timeout=300): |
| 79 | |
| 80 | r''' |
| 81 | Executes commands on the remote host |
| 82 | |
| 83 | Description of argument(s): |
| 84 | cmd Command to run on remote host |
| 85 | rtnpartial Set to True to return command output even |
| 86 | if we haven't read the command prompt |
| 87 | wait_cnt Number of times to check for command output |
| 88 | default is 5 |
| 89 | i_timeout Timeout for command output |
| 90 | default is 300 seconds |
| 91 | ''' |
| 92 | |
| 93 | # Execute the command and read the command output |
| 94 | try: |
| 95 | |
| 96 | # Flush whatever data is in the read buffer by doing |
| 97 | # a non-blocking read |
| 98 | self.tnclient.read_very_eager() |
| 99 | |
| 100 | # Execute the command |
| 101 | self.tnclient.write(cmd.encode('utf-8') + b"\n") |
| 102 | |
| 103 | # Read the command output. Read until we get command prompt |
| 104 | l_buf = '' |
| 105 | l_xcnt = 0 |
| 106 | while(True): |
| 107 | index, match, b = self.tnclient.expect([br'\$', br'\#'], i_timeout) |
| 108 | |
| 109 | if(b == ''): |
| 110 | # Nothing read. Increment the counter & retry. |
| 111 | l_xcnt = l_xcnt + 1 |
| 112 | if(l_xcnt >= wait_cnt): |
| 113 | l_time_waited = str((l_xcnt * i_timeout) / 60) |
| 114 | print("\t\t ERROR Timeout execute Telnet command") |
| 115 | break |
| 116 | else: |
| 117 | # We got some data. Reset the counter. |
| 118 | l_xcnt = 0 |
| 119 | l_buf = l_buf + b.decode('utf-8').strip() |
| 120 | |
| 121 | if (index != -1) and (match is not None): |
| 122 | # We got the command prompt. Have read the complete command |
| 123 | # output. |
| 124 | break |
| 125 | |
| 126 | if rtnpartial: |
| 127 | print("\t\t WARN " |
| 128 | + "Have not read the command prompt. " |
| 129 | + "Returning command output read.") |
| 130 | |
| 131 | return l_buf |
| 132 | except (socket.error, EOFError) as e: |
| 133 | self.tn_remoteclient_disconnect() |
| 134 | |
| 135 | if str(e).__contains__("Connection reset by peer"): |
| 136 | msg = e |
| 137 | elif str(e).__contains__("telnet connection closed"): |
| 138 | msg = "Telnet connection closed." |
| 139 | else: |
| 140 | msg = "Some other issue. Connection got reset!!" |
| 141 | |
| 142 | print("\t\t ERROR %s " % msg) |
| 143 | return '' |
| 144 | |
| 145 | # Remove command prompt |
| 146 | c = l_buf[0: (len(l_buf) - 1)] |
| 147 | return c |