def ssh_vty(self, ip, port='22'): """Setup ssh connection to the server. :param ip: ssh host/ip :param port: ssh port :return: ssh_line """ from .constants import WebserverConstants spawn = Spawn( 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ' '-l {} -p {} {} \n'.format(WebserverConstants.username, port, ip)) d1 = Dialog([ [ 'continue connecting (yes/no)?', 'sendline(yes)', None, True, False ], [ '(p|P)assword:', 'sendline({})'.format(WebserverConstants.login_password), None, False, False ], ]) try: d1.process(spawn, timeout=60) spawn.sendline() except TimeoutError: pass ssh_line = WebserverLine(spawn, self.sm, 'ssh_ftd') return ssh_line
class M4(Fmc): def __init__(self, hostname='firepower', login_username='******', login_password=KickConsts.DEFAULT_PASSWORD, sudo_password=KickConsts.DEFAULT_PASSWORD, cimc_hostname='', *args, **kwargs): """Constructor for FMC m4. :param hostname: fmc hostname or fqdn e.g. FS2000-01 or FS2000-01.cisco.com :param login_username: user name for login :param login_password: password for login :param cimc_hostname: host name in prompt in cimc scope mode e.g. C220-FCH1948V1N3 :return: None """ publish_kick_metric('device.m4.init', 1) self.patterns = M4Patterns(hostname=hostname, login_username=login_username, login_password=login_password, sudo_password=sudo_password, cimc_hostname=cimc_hostname) self.sm = M4Statemachine(self.patterns) self.line_class = M4Line self.set_default_timeout(DEFAULT_TIMEOUT) def ssh_cimc(self, ip, port, cimc_username='******', cimc_password='******', timeout=None): """This is the method to login to FMC via CIMC Interface. :param ip: FMC CIMC IP :param port: ssh port for FMC CIMC :param cimc_username: ssh username for FMC CIMC :param cimc_password: ssh password for FMC CIMC :param timeout: timeout for ssh login :return: ssh_line """ publish_kick_metric('device.m4.ssh', 1) if not timeout: timeout = self.default_timeout self.spawn_id = Spawn('ssh -o UserKnownHostsFile=/dev/null' ' -o StrictHostKeyChecking=no ' '-l {} -p {} {}'.format(cimc_username, port, ip)) d1 = Dialog([ [ 'continue connecting (yes/no)?', 'sendline(yes)', None, True, False ], [ '[Pp]assword:', 'sendline({})'.format(cimc_password), None, True, False ], [self.sm.get_state('mio_state').pattern, None, None, False, False], ]) try: d1.process(self.spawn_id, timeout=60) self.spawn_id.sendline() self.spawn_id.sendline() except TimeoutError: pass ssh_line = self.line_class(self.spawn_id, self.sm, 'ssh_cimc', timeout=timeout) logger.debug("Done: connection created by ssh {} {}".format(ip, port)) return ssh_line def reboot_cimc(self, ip, port, cimc_username='******', cimc_password='******', retries=10, interval=120): """This is the method to reboot cimc :param ip: FMC CIMC IP :param port: ssh port for FMC CIMC :param cimc_username: ssh username for FMC CIMC :param cimc_password: ssh password for FMC CIMC :param retries: polling attempts to check if CIMC is back :param interval: polling interval :return: True/False to indicate sucess """ self.ssh_cimc(ip, port, cimc_username, cimc_password) self.spawn_id.sendline("top") self.spawn_id.sendline("scope cimc") d1 = Dialog([ ['/cimc.*#', 'sendline(reboot)', None, True, False], ['Continue?.*', 'sendline(y)', None, False, False], ]) d1.process(self.spawn_id, timeout=60) logger.info("Sleeping for 60 secs..") time.sleep(60) while retries > 0: logger.info( "Wait for CIMC to be back. Attempt: {}".format(retries)) try: line = self.ssh_cimc(ip, port, cimc_username, cimc_password) if line is not None: line.disconnect() break except: logger.info("CIMC didnt respond") time.sleep(interval) retries -= 1 if retries == 0: logger.error("CIMC did not come back after reboot") return False else: return True
def is_available(host, port, user=DEFAULT_USERNAME, pwd=DEFAULT_PASSWORD, prompt='firepower login:'******'telnet'): """Checks whether device is available. :param host: Ip of the device/console :param port: console port :param user: username :param pwd: password :param prompt: expected prompt :param access: type of access: telnet or ssh :return: True if device is available, False if it's not """ if user == DEFAULT_USERNAME: user = get_username(user) if pwd == DEFAULT_PASSWORD: pwd = get_password(pwd) VALID_PROMPTS.append(prompt) if access == 'telnet': spawn_id = Spawn('telnet {} {}\n'.format(host, port)) try: spawn_id.expect( "Connected to.*Escape character is '\^\]'\..*Username: "******"Connected to.*Escape character is '\^\]'\..*Username: "******"Password: "******"Password OK.*") except TimeoutError: LOGGER.debug("'Password OK' message did not appear ... continue") spawn_id.sendline('') try: __wait_for_rommon(spawn_id, 900) except: LOGGER.info("\nFailed to get a valid prompt") spawn_id.close() return False LOGGER.info('%s on port %d is available' % (host, port)) spawn_id.close() elif access == 'ssh': try: if port is not 22: clear_line(host=host, port=port % 100, access='ssh', user=user, pwd=pwd, en_password=pwd) spawn_id = Spawn('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -l {} -p {} {}'. format(user, port, host)) d1 = Dialog([ ['continue connecting (yes/no)?', 'sendline(yes)', None, True, False], ['(P|p)assword:', 'sendline({})'.format(pwd), None, False, False], ['Connection refused', None, None, False, False], ]) d1.process(spawn_id, timeout=60) try: spawn_id.expect("Password OK.*") except: pass spawn_id.sendline() time.sleep(10) try: __wait_for_rommon(spawn_id, 900) except: LOGGER.info("\nFailed to get a valid prompt") spawn_id.close() return False LOGGER.info('%s on port %d is available' % (host, port)) spawn_id.close() except: return False else: raise RuntimeError('Device can be accessed only by telnet or ssh') return True
def clear_line(host, port, user=DEFAULT_USERNAME, pwd=DEFAULT_PASSWORD, prompt='#', access='telnet', en_password=DEFAULT_ENPASSWORD, timeout=None): """Clear line corresponding to a device; this is required because only a single console connection is available. If somebody or some process failed to close the connection, it should be cleared explicitly. This function accepts only ssh and telnet connections. :param host: ip address of terminal server :param port: device line number in terminal server to be cleared for example, if port 2005 is mapped to line 5, port=5 :param user: username :param pwd: password :param prompt: expected prompt after logging in :param access: ssh or telnet; default is set to telnet :param en_password: enable password to switch to line configuration mode :param timeout: how long the connection and authentication would take in seconds; if not provided, default is 60s :return: None """ if user == DEFAULT_USERNAME: user = get_username(user) if pwd == DEFAULT_PASSWORD: pwd = get_password(pwd) if en_password == DEFAULT_ENPASSWORD: en_password = get_password(en_password) if not timeout: timeout = DEFAULT_TIMEOUT d1 = None spawn = None # establish a connection to the terminal server if access == 'telnet': spawn = Spawn('telnet {} {}'.format(host, '23')) d1 = Dialog([ ["Connected to.*Escape character is '\^\]'\.", 'sendline()', None, True, False], ['.*Username:'******'sendline({})'.format(user), None, True, False], ['(p|P)assword:', 'sendline({})'.format(pwd), None, True, True], [prompt, 'sendline()', None, False, False], ['>', 'sendline()', None, False, False], ]) elif access == 'ssh': spawn = Spawn('ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no ' '-l {} -p {} {}'.format(user, '22', host)) d1 = Dialog([ ['continue connecting (yes/no)?', 'sendline(yes)', None, True, False], ['(p|P)assword:', 'sendline({})'.format(pwd), None, False, False], ]) else: LOGGER.error('Unknown protocol: Telnet or ssh supported only') try: LOGGER.info('Trying to connect to {}'.format(host)) d1.process(spawn, timeout=timeout) try: spawn.expect("Password OK.*") except TimeoutError: LOGGER.info("'Password OK' message didn't appear") pass spawn.sendline() except TimeoutError: LOGGER.error('Failed to connect to terminal server') raise Exception('Failed to connect to terminal server') # clear port section try: spawn.expect('#') except: # expect > spawn.sendline('en') try: spawn.expect('Password:'******'detected line number for clearing: {} from port {}'. format(line_id, port)) if line_id: spawn.sendline('clear line {}'.format(line_id)) spawn.expect('[confirm]') spawn.sendline('') spawn.expect('[OK]') LOGGER.info('line: {} was cleared'.format(port)) spawn.close() except TimeoutError: spawn.close() LOGGER.error('Line: {} was not cleared'.format(port)) raise Exception('Line {} was NOT cleared'.format(port))
import os from unicon.eal.expect import Spawn, TimeoutError router_command = os.path.join(os.getcwd(), 'router.sh') prompt = 'sim-router' enable_prompt = prompt + '#' disable_prompt = prompt + '>' s = Spawn(router_command) try: s.sendline() s.expect([r'username:\s?$', r'login:\s?$'], timeout=5) s.sendline('admin') s.expect([r'password:\s?$'], timeout=5) s.sendline('lab') s.expect([disable_prompt]) s.sendline('enable') s.expect([r'password:\s?$'], timeout=5) s.sendline('lablab') s.expect([enable_prompt]) s.sendline('show clock') s.expect([enable_prompt]) except TimeoutError as err: print('errored becuase of timeout')