Beispiel #1
0
    def test_enable_password_explicit_revert_default_enable(self):
        credentials = Credentials({
            'default': {
                'username': '******',
                'password': '******',
            },
            'mycred': {
                'username': '******',
                'password': '******',
            },
        })

        d = Connection(
            hostname='Router',
            start=['mock_device_cli --os ios '
                   '--state console_test_enable'],
            os='ios',
            connection_timeout=15,
            credentials=credentials,
            login_creds='mycred')
        with self.assertRaises(ConnectionError):
            d.connect()

        d = Connection(
            hostname='Router',
            start=['mock_device_cli --os ios '
                   '--state login_enable'],
            os='ios',
            connection_timeout=15,
            credentials=credentials,
            login_creds='mycred')
        with self.assertRaises(ConnectionError):
            d.connect()
Beispiel #2
0
    def test_enable_password_default_cred_revert_enable(self):
        credentials = Credentials({
            'default': {
                'username': '******',
                'password': '******',
            },
            'enable': {
                'password': '******'
            },
        })

        d = Connection(
            hostname='Router',
            start=['mock_device_cli --os ios '
                   '--state console_test_enable'],
            os='ios',
            connection_timeout=15,
            credentials=credentials)
        d.connect()

        d = Connection(hostname='Router',
                start=['mock_device_cli --os ios '\
                    '--state login_enable'],
                os='ios', connection_timeout=15,
                credentials=credentials
                )
        d.connect()
    def setUp(self):
        """ Prepare the mock objects for use with the tests
        """
        self.session = AttrDict()
        self.context = AttrDict({
            'default_cred_name': 'default',
            'credentials': Credentials({
                'default': {'username': '******', 'password': '******'},
                'mycred': {'username': '******', 'password': '******'},
                'enable': {'password': '******'},
            })
        })

        class MockSpawn:
            pass

        def mock_sendline(*args, **kwargs):
            print("Sendline called with: %s %s" % (args, kwargs))

        self.spawn = MockSpawn()
        self.spawn.spawn_command = 'ssh -l cisco@router'
        self.spawn.last_sent = 'ssh -l cisco@router'
        self.spawn.sendline = Mock(side_effect=mock_sendline)
        self.spawn.match = AttrDict()
        self.spawn.match.match_output = ""
        self.spawn.settings = Mock()
    def test_enable_password_explicit(self):
        credentials = Credentials({
            'default': {
                'username': '******',
                'password': '******',
                'enable_password': '******'
            },
            'mycred': {
                'username': '******',
                'password': '******',
                'enable_password': '******'
            },
            'enable': {
                'password': '******'
            },
        })

        d = Connection(hostname='Router',
                start=['mock_device_cli --os ios '\
                    '--state console_test_enable'],
                os='ios', connection_timeout=15,
                credentials=credentials,
                login_creds='mycred')
        d.connect()

        d = Connection(hostname='Router',
                start=['mock_device_cli --os ios '\
                    '--state login_enable'],
                os='ios', connection_timeout=15,
                credentials=credentials,
                login_creds='mycred')
        d.connect()
def make_testbed(name):
    testbed = Testbed(name)

    testbed.credentials = Credentials(
        dict(default=dict(username=os.environ['PYATS_USERNAME'],
                          password=os.environ['PYATS_PASSWORD'])))

    print(f"Created Genie testbed: {testbed.name}")
    return testbed
Beispiel #6
0
def make_testbed(name=__package__):
    global _g_network_testbed
    _g_network_testbed = Testbed(name)

    _g_network_testbed.credentials = Credentials(dict(default=dict(
        username=os.environ['PYATS_USERNAME'],
        password=os.environ['PYATS_PASSWORD'])))

    log.info(f"Created Genie testbed: {name}")
    return _g_network_testbed
Beispiel #7
0
    def run_server(self):
        # Run server in separate process
        signal.signal(signal.SIGINT, lambda x, y: None)
        # dict to send back in queue once server is started
        new_info = {}

        creds = self.server_info.get('credentials', {}).get('ftp', {})
        username = creds.get('username', self._generate_credential())
        password = creds.get(
            'password',
            SecretString.from_plaintext(self._generate_credential()))

        # return credentials back to parent process
        new_info['credentials'] = Credentials(
            {'ftp': {
                'username': username,
                'password': password
            }})

        address = self.server_info['address']
        port = self.server_info.get('port', DEFAULT_PORT)
        address = (address, port)
        path = self.server_info.setdefault('path', '/')
        new_info['path'] = path

        # Create FTP Server
        auth = DummyAuthorizer()
        auth.add_user(username,
                      to_plaintext(password),
                      path,
                      perm='elradfmwMT')
        handler = FTPHandler
        handler.authorizer = auth
        server = FTPServer(address, handler)
        server.max_cons = 256
        server.max_cons_per_ip = 5

        # Set up logging for the FTP Server
        logfile = self.server_info.get('logfile', None)
        if logfile:
            ftp_logger = logging.getLogger('pyftpdlib')
            ftp_logger.setLevel(logging.DEBUG)
            ftp_logger.propagate = False
            ftp_handler = logging.FileHandler(logfile)
            ftp_logger.addHandler(ftp_handler)

        # Retrieve allocated port
        _, new_info['port'] = server.address

        # Send new info back to parent process
        self.queue.put(new_info)

        # Listen
        server.serve_forever()
Beispiel #8
0
    def test_connect_ssh_no_passphrase(self):
        credentials = Credentials({'default': {'password': '******'}})

        d = Connection(hostname='Router',
                       start=[
                           'mock_device_cli --os ios '
                           '--state connect_ssh_passphrase'
                       ],
                       os='ios',
                       connection_timeout=15,
                       credentials=credentials,
                       init_exec_commands=[],
                       init_config_commands=[])

        with self.assertRaises(ConnectionError):
            d.connect()
Beispiel #9
0
    def test_connect_ssh_passphrase(self):
        credentials = Credentials(
            {'default': {
                'passphrase': 'this is a secret'
            }})

        d = Connection(hostname='Router',
                       start=[
                           'mock_device_cli --os ios '
                           '--state connect_ssh_passphrase'
                       ],
                       os='ios',
                       connection_timeout=15,
                       credentials=credentials,
                       init_exec_commands=[],
                       init_config_commands=[])
        d.connect()
        d.disconnect()
Beispiel #10
0
    def run_server(self):
        # Run server in separate process
        address = self.server_info.get('address', '0.0.0.0')
        port = self.server_info.get('port', DEFAULT_PORT)
        local_dir = self.server_info.get('path', '/')
        # use authentication by default
        http_auth = self.server_info.get('custom', {}).get('http_auth', True)

        # Setup local HTTP server
        server_address = (address, port)
        httpd = http.server.HTTPServer(server_address, HTTPRequestHandler)
        httpd.directory = local_dir
        local_port = httpd.server_port

        if http_auth:
            creds = self.server_info.get('credentials', {}).get('http', {})
            username = creds.get('username', self._generate_credential())
            password = creds.get(
                'password',
                SecretString.from_plaintext(self._generate_credential()))

            httpd.auth = base64.b64encode("{}:{}".format(
                username, to_plaintext(password)).encode()).decode()
        else:
            httpd.auth = None

        # Send new info back to parent process
        self.queue.put({
            'port': local_port,
            'path': local_dir,
            'credentials':
            Credentials({'http': {
                'username': username,
                'password': password
            }}) if http_auth else {}
        })

        # Keep process alive
        httpd.serve_forever()