Пример #1
0
def run_shell(dev, cmd):
    dev_shell = StartShell(dev)
    dev_shell.open()
    if type(cmd) == str:
        dev_shell.run('{}'.format(cmd))
        logging.log(25, 'Sending shell: [{}] to [{}].'.format(cmd, dev.facts['hostname']))
    elif type(cmd) == list:
        for entry in cmd:
            dev_shell.run('{}'.format(entry))
            logging.log(25, 'Sending shell: [{}] to [{}].'.format(entry, dev.facts['hostname']))
    dev_shell.close()
Пример #2
0
def get_hardware(host):

    dev = Device(host=host, user="******", passwd="MaRtInI", port=22)

    try:
        ss = StartShell(dev)
    except Exception as err:
        logging.error('Cannot connect to device: {0}\n'.format(err))
        return

    try:
        ss.open()
    except Exception as err:
        logging.error('Cannot open to device: {0}\n'.format(err))
        return

    cli_conf = 'cli -c "show configuration | save /var/tmp/"' + host + '.conf'
    cli_hw = 'cli -c "show chassis hardware | save /var/tmp/"' + host + '.hw'
    ss.run(cli_conf)
    ss.run(cli_hw)
    ss.close()

    remote_conf = '/var/tmp/' + host + '.conf'
    remote_hw = '/var/tmp/' + host + '.hw'

    ssh = createSSHClient(host, 22, "regress", "MaRtInI")
    scp = SCPClient(ssh.get_transport())

    scp.get(remote_conf)
    scp.get(remote_hw)
    '''
    hw = dev.rpc.get_chassis_inventory({'format':'text'}, dev_timeout=120)
    hw_filename = "hw_" + host
    file = open(hw_filename, "w")
    file.write(etree.tostring(hw))
    file.close()
    
    
    try:
        #config = dev.rpc.get_config(dev_timeout=timeout, options={'format':'set'})
        config = dev.rpc.get_config(dev_timeout=timeout)
    except Exception as err:
        logging.error('Get config error {0}\n'.format(err))
        return
        
    config_filename = "config_" + host
    file = open(config_filename, "w")
    file.write(etree.tostring(config, encoding='unicode', pretty_print=True))
    file.close()
    '''
    # End the NETCONF session and close the connection
    dev.close()
Пример #3
0
    def shell_cli_command_executor(self, **kvargs):
        # Checking if connection is alive
        self._is_connection_alive()
        command = ""
        if 'command' in kvargs:
            command = kvargs.get('command')
        if 'shelltimeout' in kvargs:
            shelltimeout = kvargs.get('shelltimeout')
        else:
            shelltimeout = 30
        if 'timeout' in kvargs:
            timeout = kvargs.get('timeout')
        else:
            timeout = 30
        shell = StartShell(self._conn, timeout=int(shelltimeout))
        shell.open()
        got = shell.run("cli -c '" + command + " | no-more'",
                        timeout=int(timeout))
        shell.close()
        if not got[0]:
            print("*WARN* %s" % (str(got[1])))
#                raise FatalError("Error executing CLI command, exiting...")
        line = re.sub('(\r\n)+', '\n', got[1])
        line = re.sub('(\r)+', '\n', line)
        line = re.sub('(\n)+', '\n', line)
        return line
Пример #4
0
    def ensure_privilege_level(self, privilege_level=None):

        """
        Ensure privilege level verifying if the current user is super-user.

        :returns:
            Returns True if success, otherwise, raise an exception (it will NOT return a false result)
        """

        log.info("Trying to ensure privilege level for user {} on host {} ... ".format(
            self.equipment_access.user, self.equipment_access.fqdn))

        try:
            # timeout: duration of time in seconds must wait for the expected result
            ss = StartShell(self.remote_conn, timeout=2)
            ss.open()
            output = ss.run('cli -c "show cli authorization"')

            # output is a tuple [bool, string], example:
            # (False, u'cli -c "show cli authorization"\r\r\nCurrent user: \'root        \' class \'super-user\ ....)
            # This string will be parsed to get the user class:

            # get the target part and split it by \n
            result = output[1].split('\n')

            # get the target part; split by '; and get the target part
            current_user_class = result[1].split("'")[3]

            if current_user_class != 'super-user':
                message = "Couldn't validate user privileges on host {}.".format(self.equipment_access.fqdn)
                log.error("{}. User {} class is '{}' and need to be 'super-user'"
                          "(close connection will be executed for safety)"
                          .format(message, self.equipment_access.user, current_user_class))
                self.close()
                raise exceptions.APIException(message)
            else:
                log.info("The privilege for user {} ('super-user') was satisfied on host {}!".format(
                    self.equipment_access.user, self.equipment_access.fqdn))
                return True

        except Exception as e:
            message = "Unknown error while verifying user privilege on host {} ".format(self.equipment_access.fqdn)
            log.error("(close connection will be executed for safety): {}".format(message, e))
            self.close()
            raise exceptions.APIException(message)
Пример #5
0
class TestStartShell(unittest.TestCase):
    @patch('paramiko.SSHClient')
    def setUp(self, mock_connect):
        self.dev = Device(host='1.1.1.1')
        self.shell = StartShell(self.dev)

    @patch('paramiko.SSHClient')
    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_open(self, mock_connect, mock_wait):
        self.shell.open()
        mock_connect.assert_called_with('(%|>)')

    @patch('paramiko.SSHClient')
    def test_startshell_close(self, mock_connect):
        self.shell._chan = MagicMock()
        self.shell._client = MagicMock()
        self.shell.close()
        self.shell._client.close.assert_called_once()

    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_run(self, mock_wait):
        self.shell._chan = MagicMock()
        self.shell.run('ls')
        self.assertTrue(call.send('echo $?') in self.shell._chan.mock_calls)

    @patch('jnpr.junos.utils.start_shell.select')
    def test_startshell_wait_for(self, mock_select):
        mock_select.return_value = ['> ', 2, 3]
        self.shell._chan = MagicMock()
        self.shell._chan.recv.return_value = '> '
        self.assertTrue(self.shell.wait_for('> ')[0].endswith('> '))

    @patch('jnpr.junos.utils.start_shell.select')
    def test_startshell_wait_for_regex(self, mock_select):
        mock_select.return_value = ['> ', 2, 3]
        self.shell._chan = MagicMock()
        #output from command: cli -c "show version"
        self.shell._chan.recv.return_value = \
        """
        ------------
        JUNOS Services Deep Packet Inspection package [15.1
        ---(more)---
        """
        self.assertTrue(
            self.shell.wait_for('---\(more\s?\d*%?\)---\n\s*|%')[0] in
            self.shell._chan.recv.return_value)

    @patch('jnpr.junos.utils.start_shell.StartShell.open')
    @patch('jnpr.junos.utils.start_shell.StartShell.close')
    def test_startshell_context(self, mock_open, mock_close):
        with StartShell(self.dev) as shell:
            shell._chan = MagicMock()
            shell.send('test')
            mock_close.assert_called_once(call())
Пример #6
0
def get_fpc_shell(dev):
	ss=StartShell(dev)
	ss.open()
	fpcs=ss.run('cli -c "show chassis fpc"')
	print(fpcs)
	for fpc in fpcs[1].strip().split('\n')[1:]:
		print(fpc)
	ss.close() 
class TestStartShell(unittest.TestCase):
    @patch('paramiko.SSHClient')
    def setUp(self, mock_connect):
        self.dev = Device(host='1.1.1.1')
        self.shell = StartShell(self.dev)

    @patch('paramiko.SSHClient')
    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_open(self, mock_connect, mock_wait):
        self.shell.open()
        mock_connect.assert_called_with('(%|>)')

    @patch('paramiko.SSHClient')
    def test_startshell_close(self, mock_connect):
        self.shell._chan = MagicMock()
        self.shell._client = MagicMock()
        self.shell.close()
        self.shell._client.close.assert_called_once()

    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_run(self, mock_wait):
        self.shell._chan = MagicMock()
        self.shell.run('ls')
        self.assertTrue(call.send('echo $?') in self.shell._chan.mock_calls)

    @patch('jnpr.junos.utils.start_shell.select')
    def test_startshell_wait_for(self, mock_select):
        mock_select.return_value = ['> ', 2, 3]
        self.shell._chan = MagicMock()
        self.shell._chan.recv.return_value = '> '
        self.assertTrue(self.shell.wait_for('> ')[0].endswith('> '))

    @patch('jnpr.junos.utils.start_shell.select')
    def test_startshell_wait_for_regex(self, mock_select):
        mock_select.return_value = ['> ', 2, 3]
        self.shell._chan = MagicMock()
        #output from command: cli -c "show version"
        self.shell._chan.recv.return_value = \
        """
        ------------
        JUNOS Services Deep Packet Inspection package [15.1
        ---(more)---
        """
        self.assertTrue(self.shell.wait_for('---\(more\s?\d*%?\)---\n\s*|%')[0]
                        in self.shell._chan.recv.return_value)

    @patch('jnpr.junos.utils.start_shell.StartShell.open')
    @patch('jnpr.junos.utils.start_shell.StartShell.close')
    def test_startshell_context(self, mock_open, mock_close):
        with StartShell(self.dev) as shell:
            shell._chan = MagicMock()
            shell.send('test')
            mock_close.assert_called_once(call())
Пример #8
0
 def set_rescue_config(self):
     """Runs the :code:`request system configuration rescue save` command for the current Juniper instance
     """
     dev = self.initialize_device()
     ss = StartShell(dev)
     ss.open()
     print("Setting rescue configuration for {}".format(self.host_name))
     cmd = ss.run('cli -c "request system configuration rescue save"')
     ss.close()
Пример #9
0
def run_cli(dev, cmd):
    dev_shell = StartShell(dev)
    dev_shell.open()
    output = str()
    if type(cmd) == str:
        output = dev_shell.run('cli -c "{}"'.format(cmd))[1]
        logging.log(25, 'Sending CLI: [{}] to [{}].'.format(cmd, dev.facts['hostname']))
    elif type(cmd) == list:
        for entry in cmd:
            output += dev_shell.run('cli -c "{}"'.format(entry))[1]
            logging.log(25, 'Sending CLI: [{}] to [{}].'.format(entry, dev.facts['hostname']))
    dev_shell.close()
    return output
Пример #10
0
    def save_config_to_file(self, **kvargs):

        directory = kvargs['directory'] + '/' + timestamp4
        print("*INFO* Saving current configuration...")
        file_obj = StartShell(self._conn)
        file_obj.open()
        got = file_obj.run("cli -c 'show configuration | save " + directory + "_config.txt' ")
        file_obj.close()
        print("*INFO* %s" % (got))
        return got[-2].split("'")[1]
Пример #11
0
 def execute_shell(self, command):
     shell = StartShell(self.device)
     try:
         shell.open()
         result = shell.run("cli -c " + "\"" + command + "\"")
         shell.close()
     except Exception as err:
         return False, err.args.__str__()
     else:
         return result[0], result[1]
Пример #12
0
def listnumcores(str1):
    if not str1:return None
    dev = Device(host = str1, user='******', password='******')
    dev.open()
    ss = StartShell(dev)
    ss.open()
    x=ss.run('cli -c "show system core-dumps |match root "')
    ss.close()
    dev.close()
    k=str(x[-1]).replace("%","")
    return k[44:]
Пример #13
0
 def healthCheck(self, A,users,password):
     if not A:
         print "not valid"
     dev = Device(host=A, user=users, passwd=password)
     try:
         dev.open()
     except Exception as err:
         self.err_list.append([A,err])
         print err
         sys.exit(1)
     self.healthcheck_list.append(dev.facts)
     ss=StartShell(dev)
     ss.open()
     ss.run('cli -c "request support information | save /var/tmp/information.txt" &')
     ss.close()
     dev.close()
Пример #14
0
def load_baseline_config(router, router_name, current_re_only):
    shellSession = StartShell(router)
    shellSession.open()
    with open('baseline_from_router.set', 'w') as base_config:
        for group in baseline_groups:
            shell_output = shellSession.run(
                'cli -c "show configuration groups ' + group +
                '| display set| no-more"')
            config = (
                shell_output[1].split('\n')
            )[1:
              -1]  # Use second element of shell_ouput list. Remove first and last line. First line is the command executed and last line is cli prompt.
            if len(config) > 0:
                for config_command in config:
                    base_config.write(config_command)
                base_config.write('set apply-groups ' + group + '\n')
        base_config.write(' set system services netconf ssh' + '\n')
    shellSession.close()

    router.open()
    facts = dict((router.facts))
    syncrhonize = False

    if not current_re_only:
        if 're0' in list(facts['current_re']):

            if facts['RE1']:
                if (str(facts['RE1']['status']) == 'OK'):
                    syncrhonize = True

        elif 're1' in list(facts['current_re']):
            if facts['RE0']:
                if (str(facts['RE0']['status']) == 'OK'):
                    syncrhonize = True

    with Config(router) as cu:
        try:
            cu.load('', overwrite=True, format="text", ignore_warning=True)
            cu.load(path='baseline_from_router.set',
                    format="set",
                    ignore_warning=True)
            cu.commit(force_sync=syncrhonize, timeout=360)
            print("Applied baseline config on ", router_name, "\n")
            router.close()
            return 0
        except Exception as e:
            print(str(e))
            print("\n\nFailed to load basedline config to ", router_name,
                  "\n\n")
            router.close()
            return 1
Пример #15
0
 def run_cmd(router_ip: str, cmd: str) -> str or bool:
     """
     This function sshes into router, runs cmd and brings the output.
     """
     # SSHing into router
     try:
         with Device(host=router_ip, user='******', port=22) as router:
             with StartShell(router) as ss:
                 response = ss.run(cmd)
     except Exception as err:
         utils.error(
             f'Error occurred when running cmd# \n{cmd}\n in router @ {router_ip}, #error:\n {err}',
         )
         return False
     return response[1]
Пример #16
0
def compare_checksum(host, dev):
    with StartShell(dev) as ss:
        try:
            b = ss.run('md5 /var/home/aprinja/12.3R12-S3.1-MOP-RC-f')
        except Exception as err:
            print('Unable to calculate checksum:', err)
        else:
            #Checksum lookup
            if b[0]:
                Local_checksum = b[1].split('\r\n')[1].split('=')[1].strip()
                if Server_checksum == Local_checksum:
                    print('The Checksum matches on: ', dev.facts['hostname'])
                else:
                    print('Checksums do not match on: ', dev.facts['hostname'])
            else:
                print("unable to calculate checksum on: ",
                      dev.facts['hostname'])
Пример #17
0
def get_vmhost_shell(dev):
    '''Login to shell mode'''
    ss = StartShell(dev)
    ss.open()
    '''Different ways to collect host output'''
    #vmhost_shell = ss.run('cli -c \'request vmhost exec "df -i"\'')
    ###Use ">show interfaces terse routing-instance all" to find out virtual instance and IP to connect to Host OS
    #vmhost_shell = ss.run('rsh -JU __juniper_private4__ 192.168.1.1 "df -i"')
    #vmhost_shell = ss.run('rsh -JU __juniper_private5__ 192.168.1.2 "df -i"')
    vmhost_shell = ss.run('vhclient "df -i"')
    #print(vmhost_shell)
    '''Print output'''
    for line in vmhost_shell[1].strip().split('\n')[1:]:
        print(line)
    '''Logout from shell mode'''
    ss.close()
Пример #18
0
def get_rsi(equipment):
    try:
        print(
            "Gathering RSI...(This takes a bit - give it time. Timeout is 10 minutes.)"
        )
        ss = StartShell(equipment)
        ss.open()
        ss.run('cli request support information \\| save /var/tmp/' +
               current_date + '_py_rsi.txt',
               this="%",
               timeout=600)
        print("RSI Done, copying it and deleting it...\n")
        ss.close()
        with SCP(equipment, progress=True) as scp:
            scp.get('/var/tmp/' + current_date + "_py_rsi.txt",
                    full_file + "_" + current_date + "_rsi.txt")
        fileSystem = FS(equipment)
        fileSystem.rm('/var/tmp/*_py_rsi.txt')
    except Exception as err:
        missedEquipment[equipment] = "Error getting RSI - " + str(err)
Пример #19
0
def getlog(str1):
    if not str1:return None
    try:
        dev = Device(host = str1, user='******', password='******')
        dev.open()
        ss = StartShell(dev)
        ss.open()
        x=ss.run('cli -c "show log messages|no-more "')
        ss.close()
        dev.close()
        with open(str1 + "log" + ".csv", 'w') as csv_file:
            csv_writer = csv.writer(csv_file, delimiter=',')
            for i in x[-1].split("\n"):
                csv_writer.writerow([i.replace("\n","")])
    except:
        print str1+" is not reachable"
        pass
    return
Пример #20
0
    def run_junos_cli_cmd(self, command, args):
        """Executes a CLI command on the Junos network device and
        returns output

        :param command: Command to run on the CLI
        :type command: str
        :param args: Name of the network device
        :type args: str
        :return: Output of the command that was ran
        :rtype: str
        """
        dev = self.connected_devices[args].open()

        logger.info('Executing CLI command: %s', command)

        with StartShell(dev) as ss:
            _, output = ss.run(r'cli -c "{} | no-more"'.format(command),
                               timeout=30)

        if output:
            output = re.sub(r'\r\n---\(more\s\d+%\)---\r\s+', '\n', output)
            output = output.replace('\r', '')
        return output
Пример #21
0
class TestStartShell(unittest.TestCase):
    @patch('paramiko.SSHClient')
    def setUp(self, mock_connect):
        self.dev = Device(host='1.1.1.1')
        self.shell = StartShell(self.dev)

    @patch('paramiko.SSHClient')
    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_open(self, mock_connect, mock_wait):
        self.shell.open()
        mock_connect.assert_called_with('% ')

    @patch('paramiko.SSHClient')
    def test_startshell_close(self, mock_connect):
        self.shell._chan = MagicMock()
        self.shell._client = MagicMock()
        self.shell.close()
        self.shell._client.close.assert_called_once()

    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_run(self, mock_wait):
        self.shell._chan = MagicMock()
        self.shell.run('ls')
        self.assertTrue(call.send('echo $?') in self.shell._chan.mock_calls)

    @patch('jnpr.junos.utils.start_shell.select')
    def test_startshell_wait_for(self, mock_select):
        mock_select.return_value = ['> ', 2, 3]
        self.shell._chan = MagicMock()
        self.assertTrue(
            call.endswith('> ') in self.shell.wait_for('> ')[0].mock_calls)

    @patch('jnpr.junos.utils.start_shell.StartShell.open')
    @patch('jnpr.junos.utils.start_shell.StartShell.close')
    def test_startshell_context(self, mock_open, mock_close):
        with StartShell(self.dev) as shell:
            shell._chan = MagicMock()
            shell.send('test')
            mock_close.assert_called_once(call())
Пример #22
0
class TestStartShell(unittest.TestCase):
    @patch('paramiko.SSHClient')
    def setUp(self, mock_connect):
        self.dev = Device(host='1.1.1.1')
        self.shell = StartShell(self.dev)

    @patch('paramiko.SSHClient')
    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_open(self, mock_connect, mock_wait):
        self.shell.open()
        mock_connect.assert_called_with('% ')

    @patch('paramiko.SSHClient')
    def test_startshell_close(self, mock_connect):
        self.shell._chan = MagicMock()
        self.shell._client = MagicMock()
        self.shell.close()
        self.shell._client.close.assert_called_once()

    @patch('jnpr.junos.utils.start_shell.StartShell.wait_for')
    def test_startshell_run(self, mock_wait):
        self.shell._chan = MagicMock()
        self.shell.run('ls')
        self.assertTrue(call.send('echo $?') in self.shell._chan.mock_calls)

    @patch('jnpr.junos.utils.start_shell.select')
    def test_startshell_wait_for(self, mock_select):
        mock_select.return_value = ['> ', 2, 3]
        self.shell._chan = MagicMock()
        self.assertTrue(call.endswith('> ') in self.shell.wait_for('> ')[0].mock_calls)

    @patch('jnpr.junos.utils.start_shell.StartShell.open')
    @patch('jnpr.junos.utils.start_shell.StartShell.close')
    def test_startshell_context(self, mock_open, mock_close):
        with StartShell(self.dev) as shell:
            shell._chan = MagicMock()
            shell.send('test')
            mock_close.assert_called_once(call())
Пример #23
0
 def add_routes_using_rtgen_mx_side(self, logicalsystem, table, subnet, count):
     '''
     Description: Routes are pumped on mx side referring to logical system and routing table, using rtgen tool.
                  Count takes integer value of number of routes.
     '''
     rtgen_cmd = 'rtgen --op add --logical-system --table --prefix --count --next-hop-type reject'
     index_words = ['--logical-system', '--table', '--prefix', '--count']
     substring_list = []
     for i in range(len(index_words)):
         substring_list.append(rtgen_cmd.find(
             index_words[i]) + len(index_words[i]))
     updated_rtgen_cmd = rtgen_cmd[:substring_list[0] + 1] + logicalsystem + rtgen_cmd[substring_list[0]:substring_list[1] + 1] + table + \
         rtgen_cmd[substring_list[1]:substring_list[2] + 1] + subnet + \
         rtgen_cmd[substring_list[2]:substring_list[3] + 1] + \
         count + rtgen_cmd[substring_list[3]:]
     mx_params = list(self.inputs.physical_routers_data.values())[0]
     dev = Device(
         host=mx_params['mgmt_ip'], user=mx_params['ssh_username'], password=mx_params['ssh_password'])
     ss = StartShell(dev)
     ss.open()
     updated_rtgen_cmd_result = ss.run(updated_rtgen_cmd)
     self.logger.debug('routes are added')
     ss.close()
Пример #24
0
    def get_enabled_interfaces(self):
        """ 
        :return: list of Physical Interfaces which read :code:`Enabled, Physical link is Down`
        :rtype: list
        """
        dev = self.initialize_device()
        ss = StartShell(dev)
        ss.open()
        cmd = ss.run('cli -c "show interfaces | match Physical | no-more"')
        ss.close()

        enabled_interfaces = []
        unchecked_interfaces = [
            'ae0', 'ae1', 'ae2', 'ae3', 'ae4', 'me0', 'vme'
        ]
        for line in cmd[1].splitlines():
            if "Enabled, Physical link is Down" in line:
                val = line.split("Physical interface: ")[1]
                val = val.split(", Enabled, Physical link is Down")[0]
                if val not in unchecked_interfaces:
                    enabled_interfaces.append(val + '.0')

        return enabled_interfaces
Пример #25
0
    def _issu_requirement_validation(self):
        """
        Checks:
            * The master Routing Engine and backup Routing Engine must be
                running the same software version before you can perform a
                unified ISSU.
            * Check GRES is enabled
            * Check NSR is enabled
            * Check commit synchronize is enabled
            * Verify that NSR is configured on the master Routing Engine
                by using the "show task replication" command.
            * Verify that GRES is enabled on the backup Routing Engine
                by using the show system switchover command.

        :returns:
            * ``True`` if validation passes.
            * * ``False`` otherwise
        """
        self.log('ISSU requirement validation: The master Routing Engine and\n'
                 'backup Routing engine must be running the same software\n'
                 'version before you can perform a unified ISSU.')
        if not (self._dev.facts['2RE'] and self._dev.facts['version_RE0']
                == self._dev.facts['version_RE1']):
            self.log('Requirement FAILED: The master Routing Engine (%s) and\n'
                     'backup Routing Engine (%s) must be running the same\n'
                     'software version before it can perform a unified ISSU' %
                     (self._dev.facts['version_RE0'],
                      self._dev.facts['version_RE1']))
            return False
        if not self._issu_nssu_requirement_validation():
            return False
        self.log('Verify that GRES is enabled on the backup Routing Engine\n'
                 'by using the command "show system switchover"')
        output = ''
        try:
            op = self._dev.rpc.request_shell_execute(
                routing_engine='backup', command="cli show system switchover")
            if op.findtext('.//switchover-state', default='').lower() == 'on':
                self.log('Graceful switchover status is On')
                return True
            output = op.findtext('.//output', default='')
        except RpcError:
            # request-shell-execute rpc is not available for <14.1
            with StartShell(self._dev) as ss:
                ss.run('cli', '> ', timeout=5)
                if ss.run('request routing-engine '
                          'login other-routing-engine')[0]:
                    # depending on user permission, prompt will go to either
                    # cli or shell, below line of code prompt will finally end
                    # up in cli mode
                    ss.run('cli', '> ', timeout=5)
                    data = ss.run('show system switchover', '> ', timeout=5)
                    output = data[1]
                    ss.run('exit')
                else:
                    self.log('Requirement FAILED: Not able run '
                             '"show system switchover"')
                    return False
        gres_status = re.search('Graceful switchover: (\w+)', output, re.I)
        if not (gres_status is not None
                and gres_status.group(1).lower() == 'on'):
            self.log('Requirement FAILED: Graceful switchover status '
                     'is not On')
            return False
        self.log('Graceful switchover status is On')
        return True
Пример #26
0
 def shell(self, cmd):
     with StartShell(self.dev) as ss:
         #cprod -A fpc0 -c "show npu memory info" >> /var/tmp/npu.stats
         result = ss.run(cmd)
         self.write_result('npu.stats', result)
Пример #27
0
 with Device(host=row["ip_address"], user=dev_username, passwd=dev_password, port='830') as dev:
     try:
         dev.open()
     except ConnectTimeoutError as err:
         print("Cannot connect to device: {0}".format(err))
         pass
     except ConnectClosedError as err:
         print("Cannot connect to device: {0}".format(err))
         pass
     except ConnectError as err:
         print("Cannot connect to device: {0}".format(err))
         pass
     f = open('results_logs.rtf', 'a+')
     f.write(row["ip_address"] + ' ' + dev.facts['hostname'])
     f.write('\n')
     with StartShell(dev, timeout=45) as ss:
         if ss.run('cli', '>')[0]:
             x = ss.run('show log messages|last 200|except "bgp|snmp|cmlc|icmp|ping|last|sshd|auto|turned|jam|craftd|auditd|ffp|handler|profile|mib2d"|no-more')
             data1 = x[1].replace('\x08', '')
             y = ss.run('show log messages.0.gz|last 200|except "bgp|snmp|cmlc|icmp|ping|last|sshd|auto|turned|jam|craftd|auditd|ffp|handler|profile|mib2d"|no-more')
             data2 = y[1].replace('\x08', '')
             if 'fpc' in data1 or 'pic' in data1 or 'interface' in data1 or 'fail' in data1 or 'power' in data1 or 'error' in data1 or 'voltage' in data1 or 'critical' in data1:
                 f.write(data1)
                 f.write('\n\n')
                 f.write(data2)
                 f.write('\n\n')
             elif 'fpc' in data2 or 'pic' in data2 or 'interface' in data2 or 'fail' in data2 or 'power' in data2 or 'error' in data2 or 'voltage' in data2 or 'critical' in data2:
                 f.write(data2)
                 f.write('\n\n')
             else:
                 f.write("Nothing to worry here")
Пример #28
0
    def get_max_connections(self):
        """Use shell commands to find maximum allowed connection-limit."""
        # the list of commands that will:
        # - exit from the command shell to the Junos CLI
        # - enter configuration mode
        # - issue the command "set system services ssh connection-limit ?",
        #     which will return help information we want to process
        # - exit configuration mode
        shell_commands = [{
            'command': 'exit',
            'prompt': '> ',
            'max': False
        }, {
            'command': 'configure',
            'prompt': '# ',
            'max': False
        }, {
            'command': 'set system services ssh connection-limit ?',
            'prompt': '# ',
            'max': True
        }, {
            'command': 'exit',
            'prompt': '> ',
            'max': False
        }]

        # open a command shell on the device
        shell = StartShell(self.dev)
        shell.open()

        # iterate over the list of commands, capturing the output from
        # the command in whose results we are interested ('max' = True)
        max_msg = None
        for shellcmd in shell_commands:
            shellout = shell.run(shellcmd['command'], shellcmd['prompt'])
            self.results['shell_results'].append(shellout)

            if shellout[0] is False:
                msg = 'Shell command "%s" did not complete as expected: %s' \
                   % (shellcmd['command'], shellout[1])
                raise RuntimeError(msg)

            if shellcmd['max']:
                max_msg = shellout[1]

        shell.close()

        # process the command output to find the max allowed value
        if max_msg is not None:
            max_arr = max_msg.splitlines()
            regex = r'connection-limit[^\(\[]*[\(\[]\d+\.\.(\d+)'
            max_str = None
            for line in max_arr:
                m = re.search(regex, line, flags=re.IGNORECASE)
                if m is not None:
                    max_str = m.group(1)
                    break

            if max_str is not None:
                reported_max = int(max_str)
                self.results['connection_max'] = reported_max
                if reported_max < self.desired_connection_limit:
                    self.results['connection_limit'] = reported_max
                else:
                    self.results['connection_limit'] = \
                       self.desired_connection_limit
            else:
                msg = 'Regex match expected but not found in command results'
                raise ValueError(msg)
        else:
            msg = 'Missing expected results from shell commands.'
            raise ValueError(msg)
Пример #29
0
 def test_startshell_context(self, mock_close, mock_open):
     with StartShell(self.dev) as shell:
         shell._chan = MagicMock()
         shell.send("test")
     mock_close.assert_called_once_with()
Пример #30
0
 def setUp(self, mock_connect):
     self.dev = Device(host="1.1.1.1")
     self.shell = StartShell(self.dev)
Пример #31
0
from jnpr.junos.utils.start_shell import StartShell
from jnpr.junos import Device
from jnpr.junos.utils.scp import SCP

dev = Device(host='xxxx', user='******', password='******')
dev.open()

ss = StartShell(dev)
ss.open()
ss.run('cli -c "request support information | save /var/tmp/information.txt"')
with SCP(dev) as scp:
    scp.get('/var/tmp/information.txt','info.txt')
    
ss.close()
from lab_devices import pe_devices, core_devices
from pprint import pprint
from jnpr.junos.utils.start_shell import StartShell

for device in pe_devices + core_devices:
    device.open()
    with StartShell(device, timeout=60) as ss:
        ospf_nei = ss.run('cli -c "show ospf neighbor"')
        print(device.hostname)
        pprint(ospf_nei)
        print()
    device.close()
Пример #33
0
 def setUp(self, mock_connect):
     self.dev = Device(host='1.1.1.1')
     self.shell = StartShell(self.dev)
Пример #34
0
class TestStartShell(unittest.TestCase):
    @patch("paramiko.SSHClient")
    def setUp(self, mock_connect):
        self.dev = Device(host="1.1.1.1")
        self.shell = StartShell(self.dev)

    @patch("paramiko.SSHClient")
    @patch("jnpr.junos.utils.start_shell.StartShell.wait_for")
    def test_startshell_open_with_shell_term(self, mock_wait, mock_connect):
        mock_wait.return_value = ["user # "]
        self.shell.open()
        mock_wait.assert_called_with("(%|>|#|\\$)")

    @patch("paramiko.SSHClient")
    @patch("jnpr.junos.utils.start_shell.StartShell.wait_for")
    def test_startshell_open_with_junos_term(self, mock_wait, mock_connect):
        mock_wait.return_value = ["user > "]
        self.shell.open()
        mock_wait.assert_called_with("(%|#|\\$)\\s")

    @patch("paramiko.SSHClient")
    @patch("jnpr.junos.utils.start_shell.StartShell.wait_for")
    def test_startshell_open_with_bourne_shell(self, mock_wait, mock_connect):
        mock_wait.return_value = ["foo@bar:~$ "]
        self.shell.open()
        mock_wait.assert_called_with("(%|>|#|\\$)")

    @patch("paramiko.SSHClient")
    def test_startshell_close(self, mock_connect):
        self.shell._chan = MagicMock()
        self.shell._client = MagicMock()
        self.shell.close()
        self.shell._client.close.assert_called_once()

    @patch("jnpr.junos.utils.start_shell.StartShell.wait_for")
    def test_startshell_run(self, mock_wait):
        self.shell._chan = MagicMock()
        mock_wait.return_value = ["user % "]
        self.shell.run("ls")
        self.assertTrue(call.send("echo $?") in self.shell._chan.mock_calls)

    @patch("jnpr.junos.utils.start_shell.select")
    def test_startshell_wait_for(self, mock_select):
        mock_select.return_value = ["> ", 2, 3]
        self.shell._chan = MagicMock()
        self.shell._chan.recv.return_value = "> "
        self.assertTrue(self.shell.wait_for("> ")[0].endswith("> "))

    @patch("jnpr.junos.utils.start_shell.select")
    def test_startshell_wait_for_regex(self, mock_select):
        mock_select.return_value = ["> ", 2, 3]
        self.shell._chan = MagicMock()
        # output from command: cli -c "show version"
        self.shell._chan.recv.return_value = """
        ------------
        JUNOS Services Deep Packet Inspection package [15.1
        ---(more)---
        """
        self.assertTrue(
            self.shell.wait_for("---\(more\s?\d*%?\)---\n\s*|%")[0] in
            self.shell._chan.recv.return_value)

    @patch("jnpr.junos.utils.start_shell.StartShell.open")
    @patch("jnpr.junos.utils.start_shell.StartShell.close")
    def test_startshell_context(self, mock_close, mock_open):
        with StartShell(self.dev) as shell:
            shell._chan = MagicMock()
            shell.send("test")
        mock_close.assert_called_once_with()

    @patch("jnpr.junos.utils.start_shell.StartShell.wait_for")
    def test_startshell_run_regex(self, mock_wait_for):
        self.shell._chan = MagicMock()
        mock_wait_for.return_value = [
            """
        ------------
        JUNOS Services Deep Packet Inspection package [15.1
        ---(more)---
        """
        ]
        self.assertTrue(
            self.shell.run("show version", "---\(more\s?\d*%?\)---\n\s*|%")[0])

    @patch("jnpr.junos.utils.start_shell.StartShell.wait_for")
    def test_startshell_run_this_None(self, mock_wait_for):
        self.shell._chan = MagicMock()
        mock_wait_for.return_value = [
            """
        ------------
        JUNOS Services Deep Packet Inspection package [15.1
        """
        ]
        self.assertTrue(self.shell.run("show version", this=None)[0])