示例#1
0
 def test_ignore_error_pattern(self):
     c = Connection(
         hostname='ncs',
         start=[
             'mock_device_cli --os confd --state juniper_exec_syntax_error'
         ],
         os='confd',
         username='******',
         tacacs_password='******')
     c.connect()
     self.assertEqual(
         c.execute('show command error', error_pattern=[]),
         '-----------------------------^\r\nsyntax error: unknown argument')
 def test_execute_show_feature(self):
     c = Connection(hostname='DellOS6',
                    start=['mock_device_cli --os dell --state exec'],
                    os='dell',
                    username='******',
                    tacacs_password='******',
                    init_exec_commands=[],
                    init_config_commands=[])
     c.connect()
     cmd = 'show ip interface'
     expected_response = mock_data['exec']['commands'][cmd].strip()
     ret = c.execute(cmd).replace('\r', '')
     self.assertIn(expected_response, ret)
示例#3
0
 def test_trim_buffer_with_execute(self):
     c = Connection(hostname='ncs',
                    start=['mock_device_cli --os confd --state cisco_exec'],
                    os='confd',
                    username='******',
                    tacacs_password='******')
     c.connect()
     c.settings.IGNORE_CHATTY_TERM_OUTPUT = True
     c.sendline('rest commit')
     r = c.execute('show services')
     self.assertEqual(
         r.replace('\r', ''), mock_data['cisco_exec']['commands']
         ['show services']['response'].rstrip())
示例#4
0
 def test_execute_with_style_option(self):
     """ Test execute command with start style cisco and execute style juniper
     Expected state after execution: cisco style
     """
     c = Connection(hostname='ncs',
                    start=['mock_device_cli --os confd --state cisco_exec'],
                    os='confd',
                    username='******',
                    tacacs_password='******')
     c.connect()
     r = c.execute('show services', style='juniper')
     c.state_machine.detect_state(c.spawn)
     self.assertEqual(c.state_machine.current_cli_style, 'cisco')
    def test_connect_syslog_messages_show_tech(self):
        conn = Connection(
            hostname='Router',
            start=[
                'mock_device_cli --os iosxr --platform spitfire --state spitfire_showtech_syslog'
            ],
            os='iosxr',
            platform='spitfire',
            mit=True)

        def sendline_wrapper(func, *args, **kwargs):
            def wrapper(*args, **kwargs):
                return func(*args, **kwargs)

            return wrapper

        conn.connect()
        conn.spawn.sendline = Mock(
            side_effect=sendline_wrapper(conn.spawn.sendline))
        conn.execute('show tech')
        conn.spawn.sendline.assert_has_calls(
            [call('show tech'), call(), call()])
 def test_learn_hostname_default(self):
     c = Connection(hostname='Router',
                         start=['mock_device_cli --os ios --state exec'],
                         os='ios', enable_password='******',
                         username='******',
                         tacacs_password='******',
                         learn_hostname=True)
     c.settings.TERM='vt100'
     c.connect()
     md = mock_device.MockDevice(device_os='ios', state='exec')
     expected_output = md.mock_data['exec']['commands']['show version'].rstrip()
     output = c.execute('show version').replace('\r', '')
     self.assertEqual(output, expected_output)
 def test_execute_show_feature(self):
     c = Connection(hostname='junos_vmx2',
                    start=['mock_device_cli --os junos --state exec'],
                    os='junos',
                    username='******',
                    tacacs_password='******',
                    init_exec_commands=[],
                    init_config_commands=[])
     c.connect()
     cmd = 'show interfaces terse | match fxp0'
     expected_response = mock_data['exec']['commands'][cmd].strip()
     ret = c.execute(cmd).replace('\r', '')
     self.assertIn(expected_response, ret)
示例#8
0
    def test_log_message_before_prompt(self):
        c = Connection(
            hostname='R1',
            start=['mock_device_cli --hostname R1 --os iosxr --state enable'],
            os='iosxr',
            username='******',
            enable_password='******',
            init_config_commands=[],
            init_exec_commands=[])
        c.connect()

        c.settings.IGNORE_CHATTY_TERM_OUTPUT = False
        c.sendline('process_restart_msg')
        r = c.execute('show telemetry | inc ACTIVE')
        self.assertIn(
            """process_restart_msg
0/RP0/ADMIN0:Jul 7 10:07:42.979 UTC: pm[2890]: %INFRA-Process_Manager-3-PROCESS_RESTART : Process tams (IID: 0) restarted""",
            r.replace('\r', ''))

        c.settings.IGNORE_CHATTY_TERM_OUTPUT = True
        c.sendline('process_restart_msg')
        r = c.execute('show telemetry | inc ACTIVE')
        self.assertEqual(r, 'Sat Jul 7 10:08:02.976 UTC\r\nState: ACTIVE')
示例#9
0
 def test_login_execution(self):
     c = Connection(
         hostname='Router',
         start=['mock_device_cli --os iosxr --state enable'],
         os='iosxr',
         credentials=dict(default=dict(username='******', password='******')))
     c.connect()
     device_output = c.execute('show version')
     with open(os.path.join(mockdata_path, 'iosxr/show_version.txt'),
               'r') as outputfile:
         expected_device_output = outputfile.read().strip()
     device_output = device_output.replace('\r', '').strip()
     self.maxDiff = None
     self.assertEqual(device_output, expected_device_output)
    def test_cisco_execute_show_services_cisco_style(self):
        c = Connection(
            hostname='ncs',
            start=['mock_device_cli --os confd --state juniper_login'],
            os='confd',
            username='******',
            tacacs_password='******')
        c.connect()
        r = c.execute('show services', style='cisco')
        self.assertEqual(
            r, """\
services sw-init-l3vpn foo
 modified devices [ CE1 PE1 ]
 directly-modified devices [ CE1 PE1 ]
 device-list [ CE1 PE1 ]""".replace('\n', '\r\n'))
    def test_reload_image_from_rommon(self):
        md = MockDeviceTcpWrapperIOSXE(port=0, state='cat9k_rommon')
        md.start()

        c = Connection(hostname='switch',
                       start=['telnet 127.0.0.1 {}'.format(md.ports[0])],
                       os='iosxe',
                       platform='cat9k',
                       mit=True,
                       settings=dict(POST_DISCONNECT_WAIT_SEC=0,
                                     GRACEFUL_DISCONNECT_WAIT_SEC=0.2),
                       credentials=dict(default=dict(username='******',
                                                     password='******'),
                                        alt=dict(username='******',
                                                 password='******')))
        try:
            c.connect()
            self.assertEqual(c.state_machine.current_state, 'rommon')
            c.execute('unlock flash:')
            c.reload(image_to_boot='tftp://1.1.1.1/latest.bin')
            self.assertEqual(c.state_machine.current_state, 'enable')
        finally:
            c.disconnect()
            md.stop()
class TestIosXrSpitfireConfigure(unittest.TestCase):
    """Tests for config prompt handling."""
    @classmethod
    def setUpClass(self):
        self._conn = Connection(
            hostname='Router',
            start=[
                'mock_device_cli --os iosxr --platform spitfire --state spitfire_enable'
            ],
            os='iosxr',
            platform='spitfire')
        self._conn.connect()

    @classmethod
    def tearDownClass(self):
        self._conn.disconnect()

    @classmethod
    def test_failed_config(self):
        """Check that we can successfully return to an enable prompt after entering failed config."""
        self._conn.execute("configure terminal", allow_state_change=True)
        self._conn.execute("test failed")
        self._conn.spawn.timeout = 60
        self._conn.enable()
示例#13
0
 def test_execute_show_feature(self):
     hostname = "Switch"
     c = Connection(hostname=hostname,
                    start=["mock_device_cli --os eos --state exec --hostname {hostname}"\
                           .format(hostname=hostname)],
                    os='eos',
                    username='******',
                    password='******',
                    init_exec_commands=[],
                    init_config_commands=[]
                    )
     c.connect()
     cmd = 'show version'
     expected_response = mock_data['exec']['commands'][cmd].strip()
     ret = c.execute(cmd).replace('\r', '')
     self.assertIn(expected_response, ret)
    def test_execute_switch_cli_with_other_commands(self):
        """ 'switch cli' together with other commands is supported
        """
        c = Connection(
            hostname='ncs',
            start=['mock_device_cli --os confd --state juniper_exec'],
            os='confd',
            username='******',
            tacacs_password='******')
        c.connect()
        r = c.execute(['switch cli', 'show services'])
        self.assertEqual(
            r['show services'], """\
services sw-init-l3vpn foo
 modified devices [ CE1 PE1 ]
 directly-modified devices [ CE1 PE1 ]
 device-list [ CE1 PE1 ]""".replace('\n', '\r\n'))
    def test_juniper_execute_show_services(self):
        c = Connection(
            hostname='ncs',
            start=['mock_device_cli --os confd --state juniper_login'],
            os='confd',
            username='******',
            tacacs_password='******')
        c.connect()
        r = c.execute('show services')
        self.assertEqual(
            r, """\
                                                                                     USED BY                                                                      
                             LSA                              LSA                    CUSTOMER                          CONFIG                                     
NAME  DEVICES      SERVICES  SERVICES  DEVICES      SERVICES  SERVICES  DEVICE LIST  SERVICE   ID  STATUS  NAME  TIME  DATA    ERROR  WHEN  TYPE  LEVEL  MESSAGE  
------------------------------------------------------------------------------------------------------------------------------------------------------------------
foo   [ CE1 PE1 ]  -         -         [ CE1 PE1 ]  -         -         [ CE1 PE1 ]  -                                                                            

[ok][2017-05-11 18:54:41]""".replace('\n', '\r\n'))
 def test_execute_show_feature(self):
     c = Connection(hostname='mlx8',
                    start=['mock_device_cli --os ironware --state exec'],
                    os='ironware',
                    credentials={
                        'default': {
                            'username': '******',
                            'password': '******'
                        },
                        'enable': {
                            'password': '******'
                        }
                    },
                    init_exec_commands=[],
                    init_config_commands=[])
     c.connect()
     cmd = 'show ip route'
     expected_response = mock_data['exec']['commands'][cmd].strip()
     ret = c.execute(cmd).replace('\r', '')
     self.assertEqual(expected_response, ret)
     c.disconnect()
示例#17
0
    def test_connect_mit_check_init_commands(self):
        c = Connection(hostname='Router',
                       start=['mock_device_cli --os ios --state login'],
                       os='ios',
                       username='******',
                       enable_password='******',
                       tacacs_password='******',
                       mit=True)

        c.setup_connection = Mock()
        c.state_machine = Mock()
        c.state_machine.states = []
        c.connection_provider = c.connection_provider_class(c)
        c.spawn = Mock()
        c.spawn.buffer = ''

        c.execute = Mock(side_effect=mock_execute)
        c.configure = Mock(side_effect=mock_configure)
        c.connect()
        assert c.execute.called == False, 'Execute was called unexpectedly'
        assert c.configure.called == False, 'Configure was called unexpectedly'
示例#18
0
    def test_config_locked(self):
        c = Connection(
            hostname='RouterRP',
            start=['mock_device_cli --os iosxe --state general_enable'],
            os='iosxe',
            mit=True,
            init_exec_commands=[],
            init_config_commands=[],
            settings=dict(POST_DISCONNECT_WAIT_SEC=0,
                          GRACEFUL_DISCONNECT_WAIT_SEC=0.2),
            log_buffer=True)
        c.connect()

        c.execute('set config lock count 2')
        c.settings.CONFIG_LOCK_RETRIES = 0
        c.settings.CONFIG_LOCK_RETRY_SLEEP = 0

        with self.assertRaises(StateMachineError):
            c.configure('')

        c.execute('set config lock count 2')
        with self.assertRaises(StateMachineError):
            c.configure('', lock_retries=1, lock_retry_sleep=1)

        c.execute('set config lock count 3')
        c.settings.CONFIG_LOCK_RETRIES = 1
        c.settings.CONFIG_LOCK_RETRY_SLEEP = 1
        with self.assertRaises(StateMachineError):
            c.configure('')

        c.execute('set config lock count 3')
        c.settings.CONFIG_LOCK_RETRIES = 5
        c.settings.CONFIG_LOCK_RETRY_SLEEP = 1
        c.configure('')

        c.disconnect()
 def test_execute_show_feature(self):
     hostname = "SLX"
     c = Connection(
         hostname=hostname,
         start=[
             'mock_device_cli --os slxos --state exec --hostname {hostname}'
             .format(hostname=hostname)
         ],
         os='slxos',
         credentials={
             'default': {
                 'username': '******',
                 'password': '******'
             }
         },
         init_exec_commands=[],
         init_config_commands=[])
     c.connect()
     cmd = 'show ip interface brief'
     expected_response = mock_data['exec']['commands'][cmd].strip()
     ret = c.execute(cmd).replace('\r', '')
     self.assertIn(expected_response, ret)
     c.disconnect()
示例#20
0
class TestIosXrPluginPrompts(unittest.TestCase):
    """Tests for prompt handling."""
    def setUp(self):
        self._conn = Connection(
            hostname='Router',
            start=['mock_device_cli --os iosxr --state enable'],
            os='iosxr',
        )
        self._conn.connect()

    def test_confirm(self):
        """Check '\n' is sent in response to a [confirm] prompt."""
        self._conn.execute("process restart ifmgr location all")

    def test_confirm_y(self):
        """Check 'y\n' is sent in response to a [y/n] prompt."""
        self._conn.execute("clear logging")

    def test_y_on_repeat_confirm(self):
        self._conn.execute("clear logg")
示例#21
0
class TestSrosPlugin(unittest.TestCase):
    def setUp(self):
        self.md = MockDevice(device_os='sros', state='execute')
        self.joined = lambda string: '\n'.join(string.splitlines())
        self.con = Connection(
            os='sros',
            hostname='Router',
            start=['mock_device_cli --os sros --state connect_ssh'],
            credentials={'default': {
                'username': '******',
                'password': '******'
            }})
        self.con.connect()

    def test_connect(self):
        self.assertIn('Router#', self.con.spawn.match.match_output)

    def test_mdcli_execute(self):
        cmd = 'show router interface coreloop'
        output = self.con.mdcli_execute(cmd)
        expect = self.md.mock_data['mdcli_execute']['commands'][cmd]
        self.assertEqual(self.joined(output), self.joined(expect))

    def test_mdcli_configure(self):
        cmd = 'router interface coreloop ipv4 primary address 1.1.1.1 prefix-length 32'
        output = self.con.mdcli_configure(cmd, mode='global')
        expect = self.md.mock_data['mdcli_configure_global']['commands'][cmd]
        # self.assertIn(self.joined(expect), self.joined(output))

    def test_mdcli_configure_commit_fail(self):
        cmd = 'router interface coreloop ipv4 primary address 2.2.2.2 prefix-length 32'
        output = self.con.mdcli_configure(cmd)
        expect = self.md.mock_data['mdcli_configure_private']['commands'][cmd]
        commit = self.md.mock_data['mdcli_configure_private']['commands'][
            'commit']
        self.assertIn(self.joined(expect), self.joined(output))
        self.assertIn(self.joined(commit), self.joined(output))

    def test_classiccli_execute(self):
        cmd = 'show router interface coreloop'
        output = self.con.classiccli_execute(cmd)
        expect = self.md.mock_data['classiccli_execute']['commands'][cmd]
        self.assertEqual(self.joined(output), self.joined(expect))

    def test_classiccli_configure(self):
        cmd = 'configure router interface coreloop address 111.1.1.1 255.255.255.255'
        output = self.con.classiccli_configure(cmd)
        expect = self.md.mock_data['classiccli_execute']['commands'][cmd][
            'response']
        self.assertIn(self.joined(expect), self.joined(output))

    def test_execute_and_cli_engine(self):
        self.con.switch_cli_engine('classiccli')
        engine = self.con.get_cli_engine()
        self.assertEqual(engine, 'classiccli')
        cmd = 'show router interface coreloop'
        output = self.con.execute(cmd)
        expect = self.md.mock_data['classiccli_execute']['commands'][cmd]
        self.assertEqual(self.joined(output), self.joined(expect))

        self.con.switch_cli_engine('mdcli')
        engine = self.con.get_cli_engine()
        self.assertEqual(engine, 'mdcli')
        cmd = 'show router interface coreloop'
        output = self.con.execute(cmd)
        expect = self.md.mock_data['mdcli_execute']['commands'][cmd]
        self.assertEqual(self.joined(output), self.joined(expect))

    def test_configure_and_cli_engine(self):
        self.con.switch_cli_engine('mdcli')
        engine = self.con.get_cli_engine()
        self.assertEqual(engine, 'mdcli')
        self.con.mdcli_configure.mode = 'global'
        cmd = 'router interface coreloop ipv4 primary address 1.1.1.1 prefix-length 32'
        output = self.con.configure(cmd)
        expect = self.md.mock_data['mdcli_configure_global']['commands'][cmd]
        # self.assertIn(self.joined(expect), self.joined(output))

        self.con.switch_cli_engine('classiccli')
        engine = self.con.get_cli_engine()
        self.assertEqual(engine, 'classiccli')
        cmd = 'configure router interface coreloop address 111.1.1.1 255.255.255.255'
        output = self.con.configure(cmd)
        expect = self.md.mock_data['classiccli_execute']['commands'][cmd][
            'response']
        self.assertIn(self.joined(expect), self.joined(output))
示例#22
0
class TestAireOsPlugin(unittest.TestCase):
    def setUp(self):
        self.c = Connection(
            hostname='Cisco Capwap Simulator',
            start=[
                'mock_device_cli --os aireos  --state aireos_exec --hostname "{}"'
                .format(hostname)
            ],
            os='aireos',
            username='******')
        self.cc = Connection(
            hostname='Cisco Capwap Simulator',
            start=[
                'mock_device_cli --os aireos  --state aireos_exec --hostname "{}"'
                .format(hostname)
            ],
            os='aireos',
            credentials=dict(default=dict(username='******', password='******')))

    def test_connect(self):
        self.c.connect()

    def test_reload(self):
        self.c.connect()
        self.c.reload()

    def test_reload_credentials(self):
        self.cc.connect()
        self.cc.reload()

    def test_restart(self):
        self.c.connect()
        self.c.reload("restart")

    def test_force_switchover(self):
        self.c.connect()
        self.c.reload("redundancy force-switchover")

    def test_press_any_key(self):
        self.c.connect()
        self.c.execute(
            "grep exclude generation 'show run-config startup-commands'")

    def test_press_enter_key(self):
        self.c.connect()
        self.c.execute("show run-config")

    def test_more(self):
        self.c.connect()
        self.c.execute("show command with more")

    def test_execute_error_pattern(self):
        for cmd in [
                'transfer upload start', 'show foo', 'debug lwapp',
                'config time ntp delete foo', 'config time ntp delete 2'
        ]:
            with self.assertRaises(SubCommandFailure) as err:
                r = self.c.execute(cmd)

    def test_save_config(self):
        self.c.connect()
        self.c.execute('save config')
示例#23
0
from unicon import Connection

# help(Connection)
vm = Connection(hostname='vm424583',
                start=['ssh 192.168.242.44'],
                username='******',
                password='******',
                os='linux')
vm.connect()
vm.connected
version = vm.execute('cat /etc/issue')
version
vm.disconnect()