Exemple #1
0
    def run_commands(self, commands, **kwargs):
        output = None
        cmds = list()
        responses = list()

        for cmd in commands:
            if output and output != cmd.output:
                responses.extend(self.execute(cmds, output=output))
                cmds = list()

            output = cmd.output
            cmds.append(str(cmd))

        if cmds:
            responses.extend(self.execute(cmds, output=output))

        for index, cmd in enumerate(commands):
            if cmd.output == 'text':
                responses[index] = responses[index].get('output')

        return responses

        data = self._get_body(commands, format)
        data = json.dumps(data)

        headers = {'Content-Type': 'application/json-rpc'}

        response, headers = fetch_url(self.url_args,
                                      self.url,
                                      data=data,
                                      headers=headers,
                                      method='POST')

        if headers['status'] != 200:
            raise NetworkError(**headers)

        try:
            response = json.loads(response.read())
        except ValueError:
            raise NetworkError('unable to load response from device')

        if 'error' in response:
            err = response['error']
            raise NetworkError(msg=err['message'],
                               code=err['code'],
                               data=err['data'],
                               commands=commands)

        if self.enable:
            response['result'].pop(0)

        return response['result']
Exemple #2
0
 def __init__(self):
     if not HAS_PYEZ:
         raise NetworkError(
             msg=
             'junos-eznc >= 1.2.2 is required but does not appear to be installed.  '
             'It can be installed using `pip install junos-eznc`')
     if not HAS_JXMLEASE:
         raise NetworkError(
             msg='jxmlease is required but does not appear to be installed.  '
             'It can be installed using `pip install jxmlease`')
     self.device = None
     self.config = None
     self._locked = False
     self._connected = False
     self.default_output = 'xml'
Exemple #3
0
 def unlock_config(self):
     try:
         self.config.unlock()
         self._locked = False
     except UnlockError:
         exc = get_exception()
         raise NetworkError('unable to unlock config: %s' % str(exc))
Exemple #4
0
 def lock_config(self):
     try:
         self.config.lock()
         self._locked = True
     except LockError:
         exc = get_exception()
         raise NetworkError('unable to lock config: %s' % str(exc))
Exemple #5
0
    def request(self, method, path, data=None, headers=None):

        headers = headers or self.DEFAULT_HEADERS

        if self.token:
            headers['X-Auth-Token'] = self.token

        if path.startswith('/'):
            path = path[1:]

        url = urlparse.urljoin(self.url, path)

        if data:
            data = json.dumps(data)

        response, headers = fetch_url(self.url_args,
                                      url,
                                      data=data,
                                      headers=headers,
                                      method=method)

        if not 200 <= headers['status'] <= 299:
            raise NetworkError(response=response, **headers)

        if int(headers['content-length']) > 0:
            if headers['content-type'].startswith('application/json'):
                response = json.load(response)
            elif headers['content-type'].startswith('text/plain'):
                response = str(response.read())

        return response
Exemple #6
0
    def connect(self, params, kickstart=True):
        host = params['host']
        port = params.get('port') or 22

        username = params['username']
        password = params.get('password')
        key_file = params.get('ssh_keyfile')
        timeout = params['timeout']

        try:
            self.shell = Shell(
                kickstart=kickstart,
                prompts_re=self.CLI_PROMPTS_RE,
                errors_re=self.CLI_ERRORS_RE,
            )
            self.shell.open(
                host, port=port, username=username, password=password,
                key_filename=key_file, timeout=timeout,
            )
        except ShellError:
            exc = get_exception()
            raise NetworkError(
                msg='failed to connect to %s:%s' % (host, port), exc=to_native(exc)
            )

        self._connected = True
Exemple #7
0
 def execute(self, commands):
     try:
         return self.shell.send(commands)
     except ShellError:
         exc = get_exception()
         commands = [str(c) for c in commands]
         raise NetworkError(to_native(exc), commands=commands)
    def __init__(self):
        if not HAS_PARAMIKO:
            raise NetworkError(
                msg='paramiko is required but does not appear to be installed.  '
                'It can be installed using  `pip install paramiko`')

        self.shell = None
        self._connected = False
Exemple #9
0
    def execute(self, commands, output='json', **kwargs):
        """Send commands to the device.
        """
        if self.url is None:
            raise NetworkError('Not connected to endpoint.')

        if self.enable is not None:
            commands.insert(0, self.enable)
Exemple #10
0
 def commit_config(self, comment=None, confirm=None):
     try:
         kwargs = dict(comment=comment)
         if confirm and confirm > 0:
             kwargs['confirm'] = confirm
         return self.config.commit(**kwargs)
     except CommitError:
         exc = get_exception()
         raise NetworkError('unable to commit config: %s' % str(exc))
Exemple #11
0
 def execute(self, commands):
     try:
         for index, item in enumerate(commands):
             commands[index] = to_command(item)
         return self.shell.send(commands)
     except ShellError:
         exc = get_exception()
         commands = [str(c) for c in commands]
         raise NetworkError(to_native(exc), commands=commands)
Exemple #12
0
    def execute(self, commands, output=None, **kwargs):
        commands = collections.deque(commands)
        output = output or self.default_output

        # only 10 commands can be encoded in each request
        # messages sent to the remote device
        stack = list()
        requests = list()

        while commands:
            stack.append(commands.popleft())
            if len(stack) == 10:
                body = self._get_body(stack, output)
                data = self._jsonify(body)
                requests.append(data)
                stack = list()

        if stack:
            body = self._get_body(stack, output)
            data = self._jsonify(body)
            requests.append(data)

        headers = {'Content-Type': 'application/json'}
        result = list()

        for req in requests:
            if self._nxapi_auth:
                headers['Cookie'] = self._nxapi_auth

            response, headers = fetch_url(self.url_args,
                                          self.url,
                                          data=data,
                                          headers=headers,
                                          method='POST')
            self._nxapi_auth = headers.get('set-cookie')

            if 'Connection failure: timed out' == headers.get('msg'):
                pass
            else:
                if headers['status'] != 200:
                    self._error(**headers)

                try:
                    response = json.loads(response.read())
                except ValueError:
                    raise NetworkError(
                        msg='unable to load response from device')

                output = response['ins_api']['outputs']['output']
                for item in to_list(output):
                    if item['code'] != '200':
                        self._error(output=output, **item)
                    else:
                        result.append(item['body'])

        return result
Exemple #13
0
    def execute(self, commands, output='json', **kwargs):
        """Send commands to the device.
        """
        if self.url is None:
            raise NetworkError('Not connected to endpoint.')

        if self.enable is not None:
            commands.insert(0, self.enable)

        body = self._get_body(commands, output)
        data = json.dumps(body)

        headers = {'Content-Type': 'application/json-rpc'}
        timeout = self.url_args['timeout']

        response, headers = fetch_url(self.url_args,
                                      self.url,
                                      data=data,
                                      headers=headers,
                                      method='POST',
                                      timeout=timeout)

        if headers['status'] != 200:
            raise NetworkError(**headers)

        try:
            response = json.loads(response.read())
        except ValueError:
            raise NetworkError('unable to load response from device')

        if 'error' in response:
            err = response['error']
            raise NetworkError(msg=err['message'],
                               code=err['code'],
                               data=err['data'],
                               commands=commands)

        if self.enable:
            response['result'].pop(0)

        return response['result']
Exemple #14
0
 def execute(self, commands):
     try:
         responses = list()
         for item in to_list(commands):
             item = self.to_command(item)
             rc, out, err = self.shell.send(item)
             if rc != 0:
                 raise ShellError(err)
             responses.append(out)
         return responses
     except ShellError as exc:
         raise NetworkError(to_native(exc))
 def run_commands(self, commands):
     cmds = list(prepare_commands(commands))
     responses = self.execute(cmds)
     for index, cmd in enumerate(commands):
         if cmd.output == 'json':
             try:
                 responses[index] = json.loads(responses[index])
             except ValueError:
                 raise NetworkError(
                     msg='unable to load response from device',
                     response=responses[index])
     return responses
Exemple #16
0
 def execute(self, commands):
     try:
         return self.shell.send(commands)
     except ShellError:
         exc = get_exception()
         cmd = ""
         if exc.command:
             cmd = "Command: %s\r\n" % str(exc.command)
         msg = str(exc.message)
         if str(exc.command) in msg:
             msg = msg.replace(str(exc.command), "")
         if "matched error in response: " in msg:
             msg = msg.replace("matched error in response: ", "")
         raise NetworkError(cmd + msg, commands=commands)
Exemple #17
0
 def run_commands(self, commands):
     cmds = list(prepare_commands(commands))
     responses = self.execute(cmds)
     for index, cmd in enumerate(commands):
         raw = cmd.args.get('raw') or False
         if cmd.output == 'json' and not raw:
             try:
                 responses[index] = json.loads(responses[index])
             except ValueError:
                 raise NetworkError(
                     msg='unable to load response from device',
                     response=responses[index],
                     command=str(cmd))
     return responses
Exemple #18
0
    def run_commands(self, commands):
        responses = list()

        for cmd in commands:
            meth = getattr(self, cmd.args.get('command_type'))
            responses.append(meth(str(cmd), output=cmd.output))

        for index, cmd in enumerate(commands):
            if cmd.output == 'xml':
                responses[index] = xml_to_json(responses[index])
            elif cmd.args.get('command_type') == 'rpc':
                responses[index] = str(responses[index].text).strip()
            elif 'RpcError' in responses[index]:
                raise NetworkError(responses[index])

        return responses
Exemple #19
0
    def run_commands(self, commands):
        """execute the ordered set of commands on the remote host

        This method will take a list of Command objects, convert them
        to a list of dict objects and execute them on the shell
        connection.

        :param commands: list of Command objects

        :returns: set of ordered responses
        """
        cmds = list(prepare_commands(commands))
        responses = self.execute(cmds)
        for index, cmd in enumerate(commands):
            if cmd.output == 'json':
                try:
                    responses[index] = json.loads(responses[index])
                except ValueError:
                    raise NetworkError(
                        msg='unable to load response from device',
                        response=responses[index])
        return responses
Exemple #20
0
    def execute(self, commands, output=None, **kwargs):
        """Send commands to the device.
        """
        commands = to_list(commands)
        output = output or self.default_output

        data = self._get_body(commands, output)
        data = self._jsonify(data)

        headers = {'Content-Type': 'application/json'}
        if self._nxapi_auth:
            headers['Cookie'] = self._nxapi_auth

        response, headers = fetch_url(self.url_args,
                                      self.url,
                                      data=data,
                                      headers=headers,
                                      method='POST')
        self._nxapi_auth = headers.get('set-cookie')

        if headers['status'] != 200:
            self._error(**headers)

        try:
            response = json.loads(response.read())
        except ValueError:
            raise NetworkError(msg='unable to load repsonse from device')

        result = list()

        output = response['ins_api']['outputs']['output']
        for item in to_list(output):
            if item['code'] != '200':
                self._error(**item)
            else:
                result.append(item['body'])

        return result
Exemple #21
0
 def _error(self, msg, **kwargs):
     self._nxapi_auth = None
     if 'url' not in kwargs:
         kwargs['url'] = self.url
     raise NetworkError(msg, **kwargs)
Exemple #22
0
 def execute(self, commands, **kwargs):
     try:
         return self.shell.send(commands)
     except ShellError:
         exc = get_exception()
         raise NetworkError(exc.message, commands=commands)
Exemple #23
0
 def _error(self, msg):
     raise NetworkError(msg, url=self.url)
Exemple #24
0
 def raise_exc(self, msg):
     if self.device:
         if self._locked:
             self.config.unlock()
         self.disconnect()
     raise NetworkError(msg)
Exemple #25
0
 def _error(self, msg, **kwargs):
     self._nxapi_auth = None
     raise NetworkError(msg, url=self.url)
Exemple #26
0
 def __init__(self):
     if not HAS_OPS:
         msg = 'ops.dc lib is required but does not appear to be available'
         raise NetworkError(msg)
     self._opsidl = None