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 waitpid(): print('\ns1> waitpid for s1') ret = os.waitpid(s1.pid, os.WNOHANG) print(ret) print('s2> waitpid for s2') ret = os.waitpid(s2.pid, os.WNOHANG) print(ret) def process(): print('\ns1> ps command output') os.system("ps -eaf | grep -i %s| grep -v grep" % s1.pid) print('s2> ps command output') os.system("ps -eaf | grep -i %s| grep -v grep" % s2.pid) print('sleeping for %s seconds ....' % sec) sleep(sec) print('\ns1> expect output ....') s1.expect(r'.*') print('\ns2> expect output ....') s2.expect(r'.*') process() #waitpid()
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')