def telnet_login(self, pri_prompt_terminator='#', alt_prompt_terminator='>', username_pattern=r"sername", pwd_pattern=r"assword", delay_factor=1, max_loops=60): """Telnet login. Can be username/password or just password.""" TELNET_RETURN = '\r\n' delay_factor = self.select_delay_factor(delay_factor) time.sleep(1 * delay_factor) output = '' return_msg = '' i = 1 while i <= max_loops: try: output = self.read_channel() return_msg += output # Search for username pattern / send username if re.search(username_pattern, output): self.write_channel(self.username + TELNET_RETURN) time.sleep(1 * delay_factor) output = self.read_channel() return_msg += output # Search for password pattern / send password if re.search(pwd_pattern, output): self.write_channel(self.password + TELNET_RETURN) time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if pri_prompt_terminator in output or alt_prompt_terminator in output: return return_msg # Check if proper data received if pri_prompt_terminator in output or alt_prompt_terminator in output: return return_msg self.write_channel(TELNET_RETURN) time.sleep(.5 * delay_factor) i += 1 except EOFError: msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg) # Last try to see if we already logged in self.write_channel(TELNET_RETURN) time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if pri_prompt_terminator in output or alt_prompt_terminator in output: return return_msg msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg)
def telnet_login(self, pri_prompt_terminator='#', alt_prompt_terminator='>', delay_factor=1, max_loops=30): """Telnet login.""" debug = False if debug: print("In telnet_login():") delay_factor = self.select_delay_factor(delay_factor) time.sleep(1 * delay_factor) output = '' i = 1 while i <= max_loops: try: read_data = self.read_channel() if debug: print(read_data) if re.search(r"sername", read_data): self.write_channel(self.username + '\n') time.sleep(1 * delay_factor) output += self.read_channel() if debug: print("Z1") print(output) elif re.search(r"assword", output): self.write_channel(self.password + "\n") output += self.read_channel() if debug: print("Z2") print(output) time.sleep(.5 * delay_factor) output += self.read_channel() if pri_prompt_terminator in output or alt_prompt_terminator in output: if debug: print("Z3") return output else: self.write_channel(u"\n") time.sleep(.5 * delay_factor) i += 1 except EOFError: msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg) msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg)
def establish_connection(self, sleep_time=3, verbose=True, timeout=8, use_keys=False, width=None, height=None): ''' Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException use_keys is a boolean that allows ssh-keys to be used for authentication ''' # Create instance of SSHClient object self.remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure appropriate for your environment) self.remote_conn_pre.set_missing_host_key_policy( paramiko.AutoAddPolicy()) # initiate SSH connection try: self.remote_conn_pre.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password, look_for_keys=use_keys, allow_agent=False, timeout=timeout) except socket.error: msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as auth_err: msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) msg += '\n' + str(auth_err) raise NetMikoAuthenticationException(msg) if verbose: print("SSH connection established to {0}:{1}".format( self.ip, self.port)) # Since Fortinet paging setting is global we need a way to disable paging # Use invoke_shell to establish an 'interactive session' if width and height: self.remote_conn = self.remote_conn_pre.invoke_shell(term='vt100', width=width, height=height) else: self.remote_conn = self.remote_conn_pre.invoke_shell() if verbose: print("Interactive SSH session established") # Strip the initial router prompt time.sleep(sleep_time) return self.remote_conn.recv(MAX_BUFFER).decode('utf-8')
def establish_connection(self, sleep_time=3, verbose=True, timeout=8, use_keys=False, key_file=None): """ Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException use_keys is a boolean that allows ssh-keys to be used for authentication """ # Convert Paramiko connection parameters to a dictionary ssh_connect_params = self._connect_params_dict(use_keys=use_keys, key_file=key_file, timeout=timeout) # Check if using SSH 'config' file mainly for SSH proxy support (updates ssh_connect_params) if self.ssh_config_file: self._use_ssh_config(ssh_connect_params) # Create instance of SSHClient object self.remote_conn_pre = paramiko.SSHClient() # Load host_keys for better SSH security if self.system_host_keys: self.remote_conn_pre.load_system_host_keys() if self.alt_host_keys and path.isfile(self.alt_key_file): self.remote_conn_pre.load_host_keys(self.alt_key_file) # Default is to automatically add untrusted hosts (make sure appropriate for your env) self.remote_conn_pre.set_missing_host_key_policy(self.key_policy) # initiate SSH connection try: self.remote_conn_pre.connect(**ssh_connect_params) except socket.error: msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as auth_err: msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port) msg += '\n' + str(auth_err) raise NetMikoAuthenticationException(msg) if verbose: print("SSH connection established to {0}:{1}".format(self.host, self.port)) # Use invoke_shell to establish an 'interactive session' self.remote_conn = self.remote_conn_pre.invoke_shell() self.remote_conn.settimeout(timeout) self.special_login_handler() if verbose: print("Interactive SSH session established") time.sleep(.1) if self.wait_for_recv_ready_newline(): return self.remote_conn.recv(MAX_BUFFER).decode('utf-8', 'ignore') return ""
def establish_connection(self, sleep_time=3, verbose=True, timeout=8, use_keys=False, key_file=None): ''' Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException use_keys is a boolean that allows ssh-keys to be used for authentication ''' # Create instance of SSHClient object self.remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure appropriate for your environment) self.remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # initiate SSH connection try: self.remote_conn_pre.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password, look_for_keys=use_keys, allow_agent=False, key_filename=key_file, timeout=timeout) except socket.error: msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as auth_err: msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) msg += '\n' + str(auth_err) raise NetMikoAuthenticationException(msg) if verbose: print("SSH connection established to {0}:{1}".format(self.ip, self.port)) # Use invoke_shell to establish an 'interactive session' self.remote_conn = self.remote_conn_pre.invoke_shell() self.special_login_handler() if verbose: print("Interactive SSH session established") time.sleep(sleep_time) # Strip any initial data if self.remote_conn.recv_ready(): return self.remote_conn.recv(MAX_BUFFER).decode('utf-8') else: i = 0 while i <= 10: # Send a newline if no data is present self.remote_conn.sendall('\n') time.sleep(.5) if self.remote_conn.recv_ready(): return self.remote_conn.recv(MAX_BUFFER).decode('utf-8') else: i += 1 return ""
def establish_connection(self, sleep_time=3, verbose=True, timeout=8, use_keys=False, key_file=None, width=None, height=None): """Special Fortinet handler for SSH connection""" self.remote_conn_pre = paramiko.SSHClient() self.remote_conn_pre.set_missing_host_key_policy( paramiko.AutoAddPolicy()) try: self.remote_conn_pre.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password, look_for_keys=use_keys, allow_agent=False, timeout=timeout) except socket.error: msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as auth_err: msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) msg += '\n' + str(auth_err) raise NetMikoAuthenticationException(msg) if verbose: print("SSH connection established to {0}:{1}".format( self.ip, self.port)) # Since Fortinet paging setting is global use terminal settings instead (if necessary) if width and height: self.remote_conn = self.remote_conn_pre.invoke_shell(term='vt100', width=width, height=height) else: self.remote_conn = self.remote_conn_pre.invoke_shell() self.remote_conn.settimeout(timeout) if verbose: print("Interactive SSH session established") i = 0 while i <= 100: time.sleep(.1) if self.remote_conn.recv_ready(): return self.remote_conn.recv(MAX_BUFFER).decode( 'utf-8', 'ignore') else: # Send a newline if no data is present self.remote_conn.sendall('\n') i += 1 return ""
def establish_connection(self, width=None, height=None): """ Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException width and height are needed for Fortinet paging setting. """ if self.protocol == 'telnet': self.remote_conn = telnetlib.Telnet(self.host, port=self.port, timeout=self.timeout) self.telnet_login() elif self.protocol == 'serial': self.remote_conn = serial.Serial(**self.serial_settings) self.serial_login() elif self.protocol == 'ssh': ssh_connect_params = self._connect_params_dict() self.remote_conn_pre = self._build_ssh_client() # initiate SSH connection try: self.remote_conn_pre.connect(**ssh_connect_params) except socket.error: msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as auth_err: msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port) msg += self.RETURN + str(auth_err) raise NetMikoAuthenticationException(msg) if self.verbose: print("SSH connection established to {0}:{1}".format( self.host, self.port)) # Use invoke_shell to establish an 'interactive session' if width and height: self.remote_conn = self.remote_conn_pre.invoke_shell( term='vt100', width=width, height=height) else: self.remote_conn = self.remote_conn_pre.invoke_shell() self.remote_conn.settimeout(self.timeout) if self.keepalive: self.remote_conn.transport.set_keepalive(self.keepalive) self.special_login_handler() if self.verbose: print("Interactive SSH session established") return ""
def _test_channel_read(self, count=40, pattern=""): """Since Keymile NOS always returns True on paramiko.connect() we check the output for substring Login incorrect after connecting.""" output = super(KeymileNOSSSH, self)._test_channel_read(count=count, pattern=pattern) pattern = r"Login incorrect" if re.search(pattern, output): self.paramiko_cleanup() msg = "Authentication failure: unable to connect" msg += "{device_type} {host}:{port}".format( device_type=self.device_type, host=self.host, port=self.port) msg += self.RESPONSE_RETURN + "Login incorrect" raise NetMikoAuthenticationException(msg) else: return output
def session_preparation(self): """ Prepare the session after the connection has been established Cisco WLC uses "config paging disable" to disable paging """ self._test_channel_read() try: self.set_base_prompt() except ValueError: msg = "Authentication failed: {}".format(self.host) raise NetMikoAuthenticationException(msg) self.disable_paging(command="config paging disable") # Clear the read buffer time.sleep(0.3 * self.global_delay_factor) self.clear_buffer()
def establish_connection(self, sleep_time=3, verbose=True, timeout=8): ''' Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException ''' # Create instance of SSHClient object self.remote_conn_pre = paramiko.SSHClient() # Automatically add untrusted hosts (make sure appropriate for your environment) self.remote_conn_pre.set_missing_host_key_policy( paramiko.AutoAddPolicy()) # initiate SSH connection if verbose: print "SSH connection established to {0}:{1}".format( self.ip, self.port) try: self.remote_conn_pre.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password, look_for_keys=False, allow_agent=False, timeout=timeout) except socket.error as e: msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as e: msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.ip, port=self.port) msg += '\n' + str(e) raise NetMikoAuthenticationException(msg) # Use invoke_shell to establish an 'interactive session' self.remote_conn = self.remote_conn_pre.invoke_shell() if verbose: print "Interactive SSH session established" # Strip the initial router prompt time.sleep(sleep_time) return self.remote_conn.recv(MAX_BUFFER)
def telnet_login(self, pri_prompt_terminator='#', alt_prompt_terminator='>', username_pattern=r"sername", pwd_pattern=r"assword", delay_factor=1, max_loops=60): """Telnet login. Can be username/password or just password.""" TELNET_RETURN = '\r\n' delay_factor = self.select_delay_factor(delay_factor) time.sleep(1 * delay_factor) output = '' return_msg = '' i = 1 while i <= max_loops: try: output = self.read_channel() return_msg += output # Search for username pattern / send username if re.search(username_pattern, output): self.write_channel(self.username + TELNET_RETURN) time.sleep(1 * delay_factor) output = self.read_channel() return_msg += output # Search for password pattern / send password if re.search(pwd_pattern, output): self.write_channel(self.password + TELNET_RETURN) time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if pri_prompt_terminator in output or alt_prompt_terminator in output: return return_msg # Support direct telnet through terminal server if re.search(r"initial configuration dialog\? \[yes/no\]: ", output): self.write_channel("no" + TELNET_RETURN) time.sleep(.5 * delay_factor) count = 0 while count < 15: output = self.read_channel() return_msg += output if re.search(r"ress RETURN to get started", output): output = "" break time.sleep(2 * delay_factor) count += 1 # Check for device with no password configured if re.search(r"assword required, but none set", output): msg = "Telnet login failed - Password required, but none set: {0}".format( self.host) raise NetMikoAuthenticationException(msg) # Check if proper data received if pri_prompt_terminator in output or alt_prompt_terminator in output: return return_msg self.write_channel(TELNET_RETURN) time.sleep(.5 * delay_factor) i += 1 except EOFError: msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg) # Last try to see if we already logged in self.write_channel(TELNET_RETURN) time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if pri_prompt_terminator in output or alt_prompt_terminator in output: return return_msg msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg)
def login_stage_2(self, username, password, menu_port=None, pri_prompt_terminator=r".*# ", alt_prompt_terminator=r".*\$ ", username_pattern=r"(?:user:|username|login|user name)", pwd_pattern=r"assword", delay_factor=1, max_loops=20): """ Perform a stage_2 login """ delay_factor = self.select_delay_factor(delay_factor) time.sleep(1 * delay_factor) output = "" return_msg = "" i = 1 menu_port_sent = False user_sent = False password_sent = False # The following prompt is only for SONiC # Need to add more login failure prompt for other system login_failure_prompt = r".*incorrect" while i <= max_loops: try: if menu_port and not menu_port_sent: self.write_and_poll("menu ports", "Selection:") self.write_channel(str(self.menu_port) + self.RETURN) menu_port_sent = True output = self.read_channel() return_msg += output # Search for username pattern / send username if not user_sent and re.search( username_pattern, output, flags=re.I): self.write_channel(username + self.RETURN) time.sleep(1 * delay_factor) output = self.read_channel() return_msg += output user_sent = True # Search for password pattern / send password if user_sent and not password_sent and re.search( pwd_pattern, output, flags=re.I): self.write_channel(password + self.RETURN) time.sleep(0.5 * delay_factor) output = self.read_channel() return_msg += output password_sent = True if re.search(pri_prompt_terminator, output, flags=re.M) or re.search( alt_prompt_terminator, output, flags=re.M): return return_msg # Check if proper data received if re.search(pri_prompt_terminator, output, flags=re.M) or re.search( alt_prompt_terminator, output, flags=re.M): return return_msg # Check if login failed if re.search(login_failure_prompt, output, flags=re.M): # Wait a short time or the next login will be refused time.sleep(1 * delay_factor) msg = "Login failed: {}".format(self.host) raise NetMikoAuthenticationException(msg) self.write_channel(self.RETURN) time.sleep(0.5 * delay_factor) i += 1 except EOFError: self.remote_conn.close() msg = "Login failed: {}".format(self.host) raise NetMikoAuthenticationException(msg) # Last try to see if we already logged in self.write_channel(self.RETURN) time.sleep(0.5 * delay_factor) output = self.read_channel() return_msg += output if re.search(pri_prompt_terminator, output, flags=re.M) or re.search( alt_prompt_terminator, output, flags=re.M): return return_msg self.remote_conn.close() msg = "Login failed: {}".format(self.host) raise NetMikoAuthenticationException(msg)
def telnet_login( self, pri_prompt_terminator=r"#\s*$", alt_prompt_terminator=r">\s*$", username_pattern=r"(?:user:|username|login|user name)", pwd_pattern=r"assword", delay_factor=1, max_loops=20, ): """Telnet login. Can be username/password or just password.""" delay_factor = self.select_delay_factor(delay_factor) time.sleep(1 * delay_factor) output = "" return_msg = "" i = 1 while i <= max_loops: try: output = self.read_channel() return_msg += output # Search for username pattern / send username if re.search(username_pattern, output, flags=re.I): self.write_channel(self.username + self.TELNET_RETURN) time.sleep(1 * delay_factor) output = self.read_channel() return_msg += output # Search for password pattern / send password if re.search(pwd_pattern, output, flags=re.I): self.write_channel(self.password + self.TELNET_RETURN) time.sleep(0.5 * delay_factor) output = self.read_channel() return_msg += output if re.search(pri_prompt_terminator, output, flags=re.M) or re.search( alt_prompt_terminator, output, flags=re.M): return return_msg # Support direct telnet through terminal server if re.search(r"initial configuration dialog\? \[yes/no\]: ", output): self.write_channel("no" + self.TELNET_RETURN) time.sleep(0.5 * delay_factor) count = 0 while count < 15: output = self.read_channel() return_msg += output if re.search(r"ress RETURN to get started", output): output = "" break time.sleep(2 * delay_factor) count += 1 # Check for device with no password configured if re.search(r"assword required, but none set", output): self.remote_conn.close() msg = "Login failed - Password required, but none set: {}".format( self.host) raise NetMikoAuthenticationException(msg) # Check if proper data received if re.search(pri_prompt_terminator, output, flags=re.M) or re.search( alt_prompt_terminator, output, flags=re.M): return return_msg self.write_channel(self.TELNET_RETURN) time.sleep(0.5 * delay_factor) i += 1 except EOFError: self.remote_conn.close() msg = "Login failed: {}".format(self.host) raise NetMikoAuthenticationException(msg) # Last try to see if we already logged in self.write_channel(self.TELNET_RETURN) time.sleep(0.5 * delay_factor) output = self.read_channel() return_msg += output if re.search(pri_prompt_terminator, output, flags=re.M) or re.search( alt_prompt_terminator, output, flags=re.M): return return_msg self.remote_conn.close() msg = "Login failed: {}".format(self.host) raise NetMikoAuthenticationException(msg)
def establish_connection(self, width=None, height=None): """ Establish SSH connection to the network device Timeout will generate a NetMikoTimeoutException Authentication failure will generate a NetMikoAuthenticationException width and height are needed for Fortinet paging setting. """ if self.protocol == 'telnet': self.remote_conn = telnetlib.Telnet(self.host, port=self.port, timeout=self.timeout) self.telnet_login() elif self.protocol == 'ssh': # Convert Paramiko connection parameters to a dictionary ssh_connect_params = self._connect_params_dict() # Check if using SSH 'config' file mainly for SSH proxy support if self.ssh_config_file: self._use_ssh_config(ssh_connect_params) # Create instance of SSHClient object self.remote_conn_pre = paramiko.SSHClient() # Load host_keys for better SSH security if self.system_host_keys: self.remote_conn_pre.load_system_host_keys() if self.alt_host_keys and path.isfile(self.alt_key_file): self.remote_conn_pre.load_host_keys(self.alt_key_file) # Default is to automatically add untrusted hosts (make sure appropriate for your env) self.remote_conn_pre.set_missing_host_key_policy(self.key_policy) # initiate SSH connection try: self.remote_conn_pre.connect(**ssh_connect_params) except socket.error: msg = "Connection to device timed-out: {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port) raise NetMikoTimeoutException(msg) except paramiko.ssh_exception.AuthenticationException as auth_err: msg = "Authentication failure: unable to connect {device_type} {ip}:{port}".format( device_type=self.device_type, ip=self.host, port=self.port) msg += '\n' + str(auth_err) raise NetMikoAuthenticationException(msg) if self.verbose: print("SSH connection established to {0}:{1}".format( self.host, self.port)) # Use invoke_shell to establish an 'interactive session' if width and height: self.remote_conn = self.remote_conn_pre.invoke_shell( term='vt100', width=width, height=height) else: self.remote_conn = self.remote_conn_pre.invoke_shell() self.remote_conn.settimeout(self.timeout) self.special_login_handler() if self.verbose: print("Interactive SSH session established") # make sure you can read the channel i = 0 delay_factor = self.select_delay_factor(delay_factor=0) main_delay = delay_factor * .1 time.sleep(main_delay) while i <= 40: new_data = self.read_channel() if new_data: break else: self.write_channel('\n') main_delay = main_delay * 1.1 if main_delay >= 8: main_delay = 8 time.sleep(main_delay) i += 1 # check if data was ever present if new_data: return "" else: raise NetMikoTimeoutException("Timed out waiting for data")
def telnet_login(self, pri_prompt_terminator='#', alt_prompt_terminator='>', delay_factor=1, max_loops=60): """Telnet login. Can be username/password or just password.""" debug = False if debug: print("In telnet_login():") delay_factor = self.select_delay_factor(delay_factor) time.sleep(1 * delay_factor) output = '' return_msg = '' i = 1 while i <= max_loops: try: output = self.read_channel() return_msg += output if debug: print(output) if re.search(r"sername", output): self.write_channel(self.username + '\n') time.sleep(1 * delay_factor) output = self.read_channel() return_msg += output if debug: print("checkpoint1") print(output) if re.search(r"assword", output): self.write_channel(self.password + "\n") time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if debug: print("checkpoint2") print(output) if pri_prompt_terminator in output or alt_prompt_terminator in output: if debug: print("checkpoint3") return return_msg if re.search(r"assword required, but none set", output): if debug: print("checkpoint4") msg = "Telnet login failed - Password required, but none set: {0}".format( self.host) raise NetMikoAuthenticationException(msg) if pri_prompt_terminator in output or alt_prompt_terminator in output: if debug: print("checkpoint5") return return_msg self.write_channel("\n") time.sleep(.5 * delay_factor) i += 1 except EOFError: msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg) # Last try to see if we already logged in self.write_channel("\n") time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if pri_prompt_terminator in output or alt_prompt_terminator in output: if debug: print("checkpoint6") return return_msg msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg)
def telnet_login(self, pri_prompt_terminator='#', alt_prompt_terminator='>', delay_factor=1, max_loops=60): """Telnet login. Can be username/password or just password.""" TELNET_RETURN = '\r\n' debug = False if debug: print("In telnet_login():") delay_factor = self.select_delay_factor(delay_factor) time.sleep(1 * delay_factor) output = '' return_msg = '' i = 1 while i <= max_loops: try: output = self.read_channel() return_msg += output if debug: print(output) if re.search(r"sername", output): self.write_channel(self.username + TELNET_RETURN) time.sleep(1 * delay_factor) output = self.read_channel() return_msg += output if debug: print("checkpoint1") print(output) if re.search(r"assword", output): self.write_channel(self.password + TELNET_RETURN) time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if debug: print("checkpoint2") print(output) if pri_prompt_terminator in output or alt_prompt_terminator in output: if debug: print("checkpoint3") return return_msg # Support direct telnet through terminal server if re.search(r"initial configuration dialog\? \[yes/no\]: ", output): if debug: print("checkpoint4") self.write_channel("no" + TELNET_RETURN) time.sleep(.5 * delay_factor) count = 0 while count < 15: output = self.read_channel() return_msg += output if re.search(r"ress RETURN to get started", output): output = "" break time.sleep(2 * delay_factor) count += 1 if re.search(r"assword required, but none set", output): if debug: print("checkpoint5") msg = "Telnet login failed - Password required, but none set: {0}".format( self.host) raise NetMikoAuthenticationException(msg) if pri_prompt_terminator in output or alt_prompt_terminator in output: if debug: print("checkpoint6") return return_msg self.write_channel(TELNET_RETURN) time.sleep(.5 * delay_factor) i += 1 except EOFError: msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg) # Last try to see if we already logged in self.write_channel(TELNET_RETURN) time.sleep(.5 * delay_factor) output = self.read_channel() return_msg += output if pri_prompt_terminator in output or alt_prompt_terminator in output: if debug: print("checkpoint6") return return_msg msg = "Telnet login failed: {0}".format(self.host) raise NetMikoAuthenticationException(msg)
def telnet_login( self, pri_prompt_terminator=r"]\s*$", alt_prompt_terminator=r">\s*$", username_pattern=r"(?:user:|username|login|user name)", pwd_pattern=r"assword", delay_factor=1, max_loops=20, ): """Telnet login for Huawei Devices""" delay_factor = self.select_delay_factor(delay_factor) password_change_prompt = re.escape("Change now? [Y/N]") combined_pattern = r"({}|{}|{})".format(pri_prompt_terminator, alt_prompt_terminator, password_change_prompt) output = "" return_msg = "" i = 1 while i <= max_loops: try: # Search for username pattern / send username output = self.read_until_pattern(pattern=username_pattern) return_msg += output self.write_channel(self.username + self.TELNET_RETURN) # Search for password pattern, / send password output = self.read_until_pattern(pattern=pwd_pattern) return_msg += output self.write_channel(self.password + self.TELNET_RETURN) # Search for router prompt, OR password_change prompt output = self.read_until_pattern(pattern=combined_pattern) return_msg += output if re.search(password_change_prompt, output): self.write_channel("N" + self.TELNET_RETURN) output = self.read_until_pattern(pattern=combined_pattern) return_msg += output return return_msg except EOFError: self.remote_conn.close() msg = "Login failed: {}".format(self.host) raise NetMikoAuthenticationException(msg) # Last try to see if we already logged in self.write_channel(self.TELNET_RETURN) time.sleep(0.5 * delay_factor) output = self.read_channel() return_msg += output if re.search(pri_prompt_terminator, output, flags=re.M) or re.search( alt_prompt_terminator, output, flags=re.M): return return_msg self.remote_conn.close() msg = "Login failed: {}".format(self.host) raise NetMikoAuthenticationException(msg)