예제 #1
0
def general_result():
    task_name = "napalm_ping"
    confirmation_result = create_result(result_content="All pings executed")
    timeouted = create_result(
        TIMEOUT_MESSAGE,
        host="R3",
        destination=IP_6,
        failed=True,
        exception=ConnectionException(f"Cannot connect to {IP_6}"),
    )
    general_result = AggregatedResult(task_name)
    general_result["R1"] = create_multi_result(
        results=[
            confirmation_result,
            ping_r1_1.create_nornir_result(),
            ping_r1_2.create_nornir_result(),
        ],
        task_name=task_name,
    )
    general_result["R2"] = create_multi_result(
        results=[confirmation_result,
                 ping_r2.create_nornir_result()],
        task_name=task_name,
    )
    general_result["R3"] = create_multi_result(
        results=[
            confirmation_result,
            ping_r3.create_nornir_result(), timeouted
        ],
        task_name=task_name,
    )
    return general_result
예제 #2
0
    def send_command_non_blocking(self,
                                  command,
                                  timeout=60,
                                  throw_exception=True):
        logging.debug('Executing commands:\n %s' % command)
        if not self.ssh:
            raise ConnectionException('Device not open')

        stdin, stdout, stderr = self.ssh.exec_command(command, timeout=timeout)
        output = ''.join(stdout.readlines())
        error = ''.join(stderr.readlines())

        if len(error) > 0:
            msg = '%s:%s' % (command, error)
            logging.debug('error:' + msg)
            if throw_exception:
                raise CommandErrorException(msg)

        regex = re.compile('ERROR:')
        if len(regex.findall(output)) > 0:
            msg = '%s:%s' % (command, output)
            logging.debug('error:' + msg)
            if throw_exception:
                raise CommandErrorException(msg)

        return output[:-1], error[:-1]  # Remove last newline charater.
예제 #3
0
    def open(self):
        """Implementation of NAPALM method open."""
        if self.transport not in TRANSPORTS:
            raise TypeError('invalid transport specified')
        klass = TRANSPORTS[self.transport]
        try:
            connection = klass(
                self.hostname,
                port=self.port,
                path=self.path,
                username=self.username,
                password=self.password,
                timeout=self.timeout,
            )
            if self.device is None:
                self.device = EapiNode(connection, enablepwd=self.enablepwd)

            sw_version = self.device.run_commands(['show version'])[0].get(
                'softwareImageVersion', "0.0.0")
            if LooseVersion(sw_version) < LooseVersion("0.14.1"):
                raise NotImplementedError(
                    "MOS Software Version 0.14.1 or better required")
            # This is to get around user mismatch in API/FileCopy
            if self._ssh is None:
                self._ssh = ConnectHandler(device_type='cisco_ios',
                                           ip=self.hostname,
                                           username=self.username,
                                           password=self.password)
                self._ssh.enable()
        except ConnectionError as ce:
            raise ConnectionException(ce.message)
예제 #4
0
def timeouted_multiresult():
    task_name = "failed_task"
    r = create_result(
        TIMEOUT_MESSAGE,
        failed=True,
        exception=ConnectionException("Cannot connect to 1.2.3.4"),
    )
    return create_multi_result([r], task_name=task_name)
예제 #5
0
    def open(self):
        """Open a connection to the device."""
        try:
            if self.transport == 'ssh':
                device_type = 'huawei'
            else:
                raise ConnectionException("Unknown transport: {}".format(self.transport))

            self.device = ConnectHandler(device_type=device_type,
                                         host=self.hostname,
                                         username=self.username,
                                         password=self.password,
                                         **self.netmiko_optional_args)
            # self.device.enable()

        except NetMikoTimeoutException:
            raise ConnectionException('Cannot connect to {}'.format(self.hostname))
예제 #6
0
파일: ros.py 프로젝트: Wofbit/napalm-ros
 def open(self):
     try:
         self.api = connect(host=self.hostname,
                            username=self.username,
                            password=self.password,
                            timeout=self.timeout)
     except (TrapError, FatalError, ConnectionError, MultiTrapError) as exc:
         raise ConnectionException(
             'Could not connect to {}:{} - [{!r}]'.format(
                 self.hostname, self.port, exc))
예제 #7
0
    def close(self):
        """Mark the connection to the device as closed."""
        delete_result, code = self._delete_token()

        if delete_result:
            self.up = False
            return True
        else:
            raise ConnectionException('Cannot connect to {}. Error {}'.format(
                self.hostname, code))
예제 #8
0
 def open(self):
     try:
         self.device = ConnectHandler(
             device_type="linux",
             host=self.hostname,
             username=self.username,
             password=self.password,
             **self.netmiko_optional_args
         )
     except NetMikoTimeoutException:
         raise ConnectionException("Cannot connect to {}".format(self.hostname))
예제 #9
0
    def open(self):
        self.device = ConnectHandler(device_type='vyos',
                                     host=self.hostname,
                                     username=self.username,
                                     password=self.password,
                                     **self.netmiko_optional_args)

        try:
            self._scp_client = SCPConn(self.device)
        except:
            raise ConnectionException("Failed to open connection ")
예제 #10
0
 def open(self):
     try:
         if self.api_key:
             self.device = pan.xapi.PanXapi(hostname=self.hostname,
                                            api_key=self.api_key)
         else:
             self.device = pan.xapi.PanXapi(hostname=self.hostname,
                                            api_username=self.username,
                                            api_password=self.password)
     except ConnectionException as e:
         raise ConnectionException(str(e))
예제 #11
0
    def _open_ssh(self):
        try:
            self.ssh_device = ConnectHandler(device_type='paloalto_panos',
                                             ip=self.hostname,
                                             username=self.username,
                                             password=self.password,
                                             **self.netmiko_optional_args)
        except ConnectionException as e:
            raise ConnectionException(str(e))

        self.ssh_connection = True
예제 #12
0
 def _send_command(self, command):
     try:
         if isinstance(command, list):
             for cmd in command:
                 output = self.device.send_command(cmd)
                 if "% Invalid" not in output:
                     break
         else:
             output = self.device.send_command(command)
         return output
     except (socket.error, EOFError) as e:
         raise ConnectionException(str(e))
예제 #13
0
 def open(self):
     """
     Implementation of NAPALM method 'open' to open a connection to the device.
     """
     try:
         self.session_info = dict(s=pyaoscx.session.login(
             self.base_url, self.username, self.password),
                                  url=self.base_url)
         self.isAlive = True
     except ConnectionError as error:
         # Raised if device not available or HTTPS REST is not enabled
         raise ConnectionException(str(error))
예제 #14
0
 def open(self):
     """Implementation of NAPALM method open."""
     try:
         self.device = EXOS(hostname=self.hostname,
                            username=self.username,
                            password=self.password,
                            port=self.port,
                            timeout=self.timeout)
         self.device.open()
     except Exception:
         raise ConnectionException("Unable to connect to {0}".format(
             self.hostname))
예제 #15
0
 def open(self):
     try:
         self.device = NXOSDevice(host=self.hostname,
                                  username=self.username,
                                  password=self.password,
                                  timeout=self.timeout,
                                  port=self.port,
                                  transport=self.transport,
                                  verify=self.ssl_verify,
                                  api_format="jsonrpc")
         self._send_command('show hostname')
     except (NXAPIConnectionError, NXAPIAuthError):
         # unable to open connection
         raise ConnectionException('Cannot connect to {}'.format(self.hostname))
예제 #16
0
 def open(self):
     try:
         self.device = NXOSDevice(self.hostname,
                                  self.username,
                                  self.password,
                                  timeout=self.timeout,
                                  port=self.port,
                                  transport=self.transport)
         self.device.show('show hostname')
         self.up = True
     except (CLIError, ValueError):
         # unable to open connection
         raise ConnectionException('Cannot connect to {}'.format(
             self.hostname))
예제 #17
0
 def open(self):
     """Connect with the device."""
     try:
         self.device = ConnectHandler(
             device_type="cisco_ios_telnet",
             ip=self.hostname,
             port=self.port,
             username=self.username,
             password=self.password,
             timeout=self.timeout,
             verbose=True,
         )
     except Exception:
         raise ConnectionException(
             "Cannot connect to switch: %s:%s" % (self.hostname, self.port)
         )
예제 #18
0
    def open(self):
        """
        Open a connection to the device.

        This method can be used to verify if the device is reachable
        and credentials are valid before moving on to other, more complex,
        requests.
        """
        auth_result, code = self._authenticate()
        if auth_result:
            self.up = True
            return True
        else:
            self.up = False
            raise ConnectionException('Cannot connect to {}. Error {}'.format(
                self.hostname, code))
예제 #19
0
 def delete_token(self):
     """Delete auth token."""
     full_url = self.base_url + "/tokenservices/{}".format(self.token)
     try:
         token_delete_request = self.session.delete(full_url,
                                                    auth=(self.username,
                                                          self.password),
                                                    timeout=self.timeout,
                                                    verify=False)
         if token_delete_request.status_code is 204:
             self.session.headers.pop('X-Auth-Token', None)
             return (True, None)
         else:
             return (False, token_delete_request.status_code)
     except requests.exceptions.RequestException as e:
         raise ConnectionException(py23_compat.text_type(e))
예제 #20
0
파일: ros.py 프로젝트: sHorst/napalm-ros
 def open(self):
     method = self.optional_args.get('login_method', 'plain')
     method = getattr(librouteros.login, method)
     try:
         self.api = connect(
             host=self.hostname,
             username=self.username,
             password=self.password,
             port=self.port,
             timeout=self.timeout,
             login_method=method,
             ssl_wrapper=self.ssl_wrapper,
         )
     except (TrapError, FatalError, socket.timeout, socket.error, MultiTrapError) as exc:
         # pylint: disable=raise-missing-from
         raise ConnectionException(f"Could not connect to {self.hostname}:{self.port} - [{exc!r}]")
예제 #21
0
    def send_command_std(self, command, timeout=60, throw_exception=True):
        logging.debug('Executing commands:\n %s' % command)
        if not self.ssh:
            raise ConnectionException('Device not open')

        chan = self.ssh.get_transport().open_session()
        chan.settimeout(timeout)
        chan.exec_command(command)
        retcode = chan.recv_exit_status()
        logging.debug('Command exited with code %d' % retcode)

        error_chan = chan.makefile_stderr()
        output_chan = chan.makefile()

        error = ''
        output = ''

        for e in error_chan.read():
            error = error + self._read_wrapper(e)

        logging.debug("stderr: " + error)

        for o in output_chan.read():
            output = output + self._read_wrapper(o)

        logging.debug("stdout: " + output)

        # Ignore stty error happen in some devices
        if "stty: standard input: Inappropriate ioctl for device" in error:
            error = error.replace(
                'stty: standard input: Inappropriate ioctl for device\n', '')

        if len(error) > 0 and retcode != 0:
            msg = '%s:%s' % (command, error)
            logging.debug('error:' + msg)
            if throw_exception:
                raise CommandErrorException(msg)

        regex = re.compile('ERROR:')
        if len(regex.findall(output)) > 0:
            msg = '%s:%s' % (command, output)
            logging.debug('error:' + msg)
            if throw_exception:
                raise CommandErrorException(msg)
        return output[:-1], error[:
                                  -1], retcode  # Remove last newline charater.
 def open(self):
     """Establish connection with the network device."""
     log.debug(
         "Establishing the connection over gRPC as %s@%s:%d",
         self.username,
         self.hostname,
         self.port,
     )
     kwargs = {}
     if self.tls_key and self.tls_server_name:
         kwargs = {"creds": self.tls_key, "options": self.tls_server_name}
     self.driver = CiscoGRPCClient(self.hostname, self.port, self.timeout,
                                   self.username, self.password, **kwargs)
     log.debug('Executing "show clock" to check the connection')
     try:
         self._execute("showcmdtextoutput", "show clock", format="text")
     except NapalmException as err:
         raise ConnectionException(err)
예제 #23
0
    def open(self):
        """Open a connection to the device."""
        try:
            device_type = 'cisco_ios'
            if self.transport == "telnet":
                device_type = "cisco_ios_telnet"

            self.device = ConnectHandler(device_type=device_type,
                                         host=self.hostname,
                                         username=self.username,
                                         password=self.password,
                                         **self.netmiko_optional_args)
            self.default_clipaging_status = self._get_clipaging_status()
            if self.disable_paging and self.default_clipaging_status == 'enable':
                self.device.disable_paging(command="disable clipaging")

        except NetMikoTimeoutException:
            raise ConnectionException('Cannot connect to {}'.format(self.hostname))
예제 #24
0
    def open(self):
        """Implementation of NAPALM method open."""
        try:
            connection = self.transport_class(host=self.hostname,
                                              username=self.username,
                                              password=self.password,
                                              timeout=self.timeout,
                                              **self.eapi_kwargs)
            if self.device is None:
                self.device = EapiNode(connection, enablepwd=self.enablepwd)

            sw_version = self.device.run_commands(["show version"])[0].get(
                "softwareImageVersion", "0.0.0")
            if LooseVersion(sw_version) < LooseVersion("0.17.9"):
                raise NotImplementedError(
                    "MOS Software Version 0.17.9 or better required")
            self._version = LooseVersion(sw_version)
        except ConnectionError as ce:
            raise ConnectionException(ce.message)
예제 #25
0
 def open(self):
     """Implement the NAPALM method open (mandatory)"""
     try:
         device_type = "cisco_ios"
         #if self.transport == "telnet":
         #    device_type = "hios_telnet"
         self.device = ConnectHandler(
             device_type=device_type,
             host=self.hostname,
             username=self.username,
             password=self.password,
             session_log="log",
             **self.netmiko_optional_args
         )
         # ensure in enable mode
         self.device.enable()
     except Exception:
         raise ConnectionException("Cannot connect to switch: %s:%s" % (self.hostname,
                                                                        self.port))
예제 #26
0
    def get_resp(self,
                 endpoint="",
                 data=None,
                 params={},
                 throw=True,
                 returnObject=False):
        """Get response from device and returne parsed json."""
        full_url = self.base_url + endpoint
        f = None
        try:
            if data is not None:
                f = self.session.post(full_url,
                                      data=data,
                                      auth=(self.username, self.password),
                                      headers=self.headers,
                                      timeout=self.timeout,
                                      params=params,
                                      verify=False)
            else:
                f = self.session.get(full_url,
                                     auth=(self.username, self.password),
                                     headers=self.headers,
                                     timeout=self.timeout,
                                     params=params,
                                     verify=False)
            if (f.status_code != 200):
                if throw:
                    errMsg = "Operation returned an error: {}".format(
                        f.status_code)
                    raise CommandErrorException(errMsg)
                else:
                    return False

            if returnObject:
                return f
            else:
                return f.text
        except requests.exceptions.RequestException as e:
            if throw:
                raise ConnectionException(py23_compat.text_type(e))
            else:
                return False
예제 #27
0
 def get_auth_token(self):
     """ Authenticate with user and password to get an auth token."""
     full_url = self.base_url + "/tokenservices"
     try:
         token_request = self.session.post(full_url,
                                           auth=(self.username,
                                                 self.password),
                                           data="",
                                           timeout=self.timeout,
                                           verify=False)
         if token_request.status_code is 204 and 'X-Auth-Token' in token_request.headers.keys(
         ):
             self.token = token_request.headers['X-Auth-Token']
             self.session.headers.update(
                 {'X-Auth-Token': token_request.headers['X-Auth-Token']})
             return (True, None)
         else:
             return (False, token_request.status_code)
     except requests.exceptions.RequestException as e:
         raise ConnectionException(py23_compat.text_type(e))
예제 #28
0
    def _process_optional_args(self, optional_args):
        self.enablepwd = optional_args.pop("enable_password", "")
        self.config_timeout = optional_args.pop("config_timeout", 300)

        transport = optional_args.get(
            "transport", optional_args.get("eos_transport", "https"))
        try:
            self.transport_class = pyeapi.client.TRANSPORTS[transport]
        except KeyError:
            raise ConnectionException("Unknown transport: {}".format(
                self.transport))
        init_args = inspect.getfullargspec(self.transport_class.__init__)[0]
        init_args.pop(0)  # Remove "self"
        init_args.append(
            "enforce_verification")  # Not an arg for unknown reason

        filter_args = ["host", "username", "password", "timeout"]

        self.eapi_kwargs = {
            k: v
            for k, v in optional_args.items()
            if k in init_args and k not in filter_args
        }
예제 #29
0
    def open(self):
        """
        Opens a connection to the device.
        """
        try:
            self.device = ConnectHandler(
                device_type='ruckus_fastiron',
                ip=self.hostname,  # saves device parameters
                port=self.port,
                username=self.username,
                password=self.password,
                timeout=self.timeout,
                verbose=True)
            self.device.session_preparation()
            # image_type = self.device.send_command("show version")   # find the image type
            # if image_type.find("SPS") != -1:
            #     self.image_type = "Switch"
            # else:
            #     self.image_type = "Router"

        except Exception:
            raise ConnectionException("Cannot connect to switch: %s:%s" %
                                      (self.hostname, self.port))
예제 #30
0
    def get_resp(self, endpoint="", data=None):
        """Get response from device and returne parsed json."""
        full_url = self.base_url + endpoint
        f = None
        try:
            if data is not None:
                f = self.session.post(full_url,
                                      data=data,
                                      headers=self.headers,
                                      timeout=self.timeout,
                                      verify=False)
            else:
                f = self.session.get(full_url,
                                     headers=self.headers,
                                     timeout=self.timeout,
                                     verify=False)
            if (f.status_code != 200):
                raise CommandErrorException(
                    "Operation returned an error: {}".format(f.status_code))

            return f.json()
        except requests.exceptions.RequestException as e:
            raise ConnectionException(py23_compat.text_type(e))