Example #1
0
    def exec_command(self, request):
        """Sends the request to the node and returns the reply
        The method accepts two forms of request.  The first form is as a byte
        string that represents xml string be send over netconf session.
        The second form is a json-rpc (2.0) byte string.
        """
        try:
            obj = json.loads(to_text(request, errors='surrogate_or_strict'))

            if 'jsonrpc' in obj:
                if self._netconf:
                    out = self._exec_rpc(obj)
                else:
                    out = self.internal_error("netconf plugin is not supported for network_os %s" % self._play_context.network_os)
                return 0, to_bytes(out, errors='surrogate_or_strict'), b''
            else:
                err = self.invalid_request(obj)
                return 1, b'', to_bytes(err, errors='surrogate_or_strict')

        except (ValueError, TypeError):
            # to_ele operates on native strings
            request = to_native(request, errors='surrogate_or_strict')

        req = to_ele(request)
        if req is None:
            return 1, b'', b'unable to parse request'

        try:
            reply = self._manager.rpc(req)
        except RPCError as exc:
            return 1, b'', to_bytes(to_xml(exc.xml), errors='surrogate_or_strict')

        return 0, to_bytes(reply.data_xml, errors='surrogate_or_strict'), b''
Example #2
0
    def _push(self, configuration):
        config = new_ele('config')
        config.append(configuration.root)

        self.logger.info("Sending edit : {}".format(to_xml(config)))
        try:
            self.netconf.edit_config(target="candidate", config=config)
        except RPCError as e:
            self.logger.info("An RPCError was raised : {}".format(e))
            raise
Example #3
0
 def rpc(self, name):
     """RPC to be execute on remote device
        :name: Name of rpc in string format"""
     try:
         obj = to_ele(name)
         resp = self.m.rpc(obj)
         return resp.data_xml if hasattr(resp, 'data_xml') else resp.xml
     except RPCError as exc:
         msg = exc.data_xml if hasattr(exc, 'data_xml') else exc.xml
         raise Exception(to_xml(msg))
Example #4
0
def get_config(module, config_filter=None, source='running'):
    conn = get_connection(module)

    # Note: Does not cache config in favour of latest config on every get operation.
    out = conn.get_config(source=source, filter=config_filter)
    if is_netconf(module):
        out = to_xml(conn.get_config(source=source, filter=config_filter))

    cfg = out.strip()

    return cfg
Example #5
0
    def get_device_info(self):
        device_info = dict()
        device_info['network_os'] = 'junos'
        ele = new_ele('get-software-information')
        data = self.execute_rpc(to_xml(ele))
        reply = to_ele(data)
        sw_info = reply.find('.//software-information')

        device_info['network_os_version'] = self.get_text(sw_info, 'junos-version')
        device_info['network_os_hostname'] = self.get_text(sw_info, 'host-name')
        device_info['network_os_model'] = self.get_text(sw_info, 'product-model')

        return device_info
Example #6
0
    def load_configuration(self, *args, **kwargs):
        """Loads given configuration on device
        :format: Format of configuration (xml, text, set)
        :action: Action to be performed (merge, replace, override, update)
        :target: is the name of the configuration datastore being edited
        :config: is the configuration in string format."""
        if kwargs.get('config'):
            kwargs['config'] = to_bytes(kwargs['config'], errors='surrogate_or_strict')
            if kwargs.get('format', 'xml') == 'xml':
                kwargs['config'] = to_ele(kwargs['config'])

        try:
            return self.m.load_configuration(*args, **kwargs).data_xml
        except RPCError as exc:
            raise Exception(to_xml(exc.xml))
Example #7
0
    def exec_command(self, request, in_data=None, sudoable=True):
        """Sends the request to the node and returns the reply
        The method accepts two forms of request.  The first form is as a byte
        string that represents xml string be send over netconf session.
        The second form is a json-rpc (2.0) byte string.
        """
        if self._manager:
            # to_ele operates on native strings
            request = to_ele(to_native(request, errors='surrogate_or_strict'))

            if request is None:
                return 'unable to parse request'

            try:
                reply = self._manager.rpc(request)
            except RPCError as exc:
                error = self.internal_error(data=to_text(to_xml(exc.xml), errors='surrogate_or_strict'))
                return json.dumps(error)

            return reply.data_xml
        else:
            return self._local.exec_command(request, in_data, sudoable)
def demo(host=nc_host, port=nc_port, user=nc_user, password=nc_password):
    with manager.connect(host=host, port=port, username=user, password=password, hostkey_verify=False, look_for_keys=False, allow_agent=False) as m:
		res = m.get(("subtree", filter_snippet))
		print xml_.to_xml(res.data_ele, pretty_print=True)
def demo(host="127.0.0.1", port = 2022, user="******", password = "******"):
	with manager.connect(host=host, port=port, username=user, password=password, unknown_host_cb=default_unknown_host_cb) as m:
		res = m.get(("subtree", filter_snippet))
		print xml_.to_xml(res.data_ele, pretty_print=True)
def get_children_by_unqualified_tag(tag, node, excluding):
    for child in node:
        if child not in excluding and unqualify(child.tag) == tag:
            return child

    raise AssertionError("Missing element {} in {}".format(tag, to_xml(node, pretty_print=True)))
 def describe_mismatch(self, item, mismatch_description):
     itemxml = item if not isinstance(item, basestring) else to_ele(item)
     mismatch_description.append_text("WAS : \n" + to_xml(itemxml, pretty_print=True) + "\n\n")
     mismatch_description.append_text("IN WHICH : " + str(self.last_error))
Example #12
0
 def discard_changes(self, *args, **kwargs):
     try:
         response = self.m.discard_changes(*args, **kwargs)
         return to_xml(remove_namespaces(response))
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #13
0
 def commit(self, *args, **kwargs):
     try:
         return self.m.commit(*args, **kwargs).data_xml
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #14
0
 def execute_nc_cli(self, *args, **kwargs):
     try:
         return self.m.cli(*args, **kwargs).xml
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #15
0
 def edit_config(self, *args, **kwargs):
     try:
         return self.m.edit_config(*args, **kwargs).xml
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
def nx_config_precheck(HOST, PORT, USER, PASS, INTERFACE, IFVLAN, DEBUGON):
    # This Routine connects to a Nexus Device and performs pre-check operations. These pre-check operations
    # validate that there are no conflicting elements to the port such as "its online" as well as
    # order of operation checks like the desired VLAN that the port is to be assigned is created.
    # Why we do this.. If the VLAN doesnt exist the aplication of the VLAN on the access port
    # will not happen correctly so thats why we want to run pre-checks.

    with manager.connect(host=HOST,
                         port=PORT,
                         username=USER,
                         password=PASS,
                         hostkey_verify=False,
                         device_params={
                             'name': 'nexus',
                             "ssh_subsystem_name": "netconf"
                         },
                         look_for_keys=False,
                         allow_agent=False) as m:
        # Get all VLANs that exists on the Device. Parse VLANs and compare against the VLAN List
        vlan_filter = '''
		<System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
            <bd-items>
                <bd-items>
                    <BD-list>
                        <fabEncap/>
                    </BD-list>
                </bd-items>
            </bd-items>
		</System>'''
        vlanres = m.get(('subtree', vlan_filter))
        if (DEBUGON):
            print(xml_.to_xml(vlanres.data_ele, pretty_print=True))
        # Parse the number of VLANs returned by the VLAN filter and add the results into a
        # dictionary, format the dictionary as KVP's with the vlan {'vlan-5' : 'vlan-5'}
        xml_doc = xml.dom.minidom.parseString(vlanres.xml)
        numofvlans = xml_doc.getElementsByTagName('fabEncap').length
        vlans = xml_doc.getElementsByTagName('fabEncap')
        switchvlanrange = {}
        for count in range(numofvlans):
            switchvlanrange[str(vlans[count].firstChild.nodeValue)] = str(
                vlans[count].firstChild.nodeValue)
        # Take the user requested VLAN range and break up the range values to provide an ordered
        # list, take the list and convert it into a dictionaory that is formatted in a
        # similar way to the switch result, with the vlan-### : vlan-### in the key value pairs
        VLANIDs = str(IFVLAN)
        VLANIDs = VLANIDs.join(VLANIDs.split())
        r = set()
        for x in VLANIDs.split(','):
            t = x.split('-')
            if len(t) not in [1, 2]:
                raise SyntaxError("hash_range is given its arguement as " +
                                  VLANIDs +
                                  " which seems not correctly formated.")
            r.add(int(t[0])) if len(t) == 1 else r.update(
                set(range(int(t[0]),
                          int(t[1]) + 1)))
        l = list(r)
        l.sort()
        vlanrange = {}
        for myelement in l:
            vlanrange['vlan-' + str(myelement)] = 'vlan-' + str(myelement)
        # Now compare the two dictionaries. The user requested vlans should be a subset of
        # the overall available VLANs on the switch. If not then data will not pass correctly
        if (DEBUGON):
            print("User Range")
            print(vlanrange)
            print("On Switch Range")
            print(switchvlanrange)
        if (set(vlanrange).issubset(set(switchvlanrange)) == False):
            sys.exit(
                "At least 1 VLAN in the Range: \"" + str(IFVLAN) +
                "\" does not exist in the switch. Terminating without changes")
        if (DEBUGON):
            print("VLAN Check OK")

        # Second Test: Check if Interface is currently UP.. if so this could be damaging
        int_filter = '''
        <System xmlns="http://cisco.com/ns/yang/cisco-nx-os-device">
            <intf-items>
                <phys-items>
                    <PhysIf-list>
                        <id>''' + INTERFACE + '''</id>   
                    </PhysIf-list>
                </phys-items>
            </intf-items>
        </System>
        '''
        res = m.get(('subtree', int_filter))
        # print (xml_.to_xml(res.data_ele, pretty_print=True))
        xml_doc = xml.dom.minidom.parseString(res.xml)
        INT_UP = xml_doc.getElementsByTagName('operSt')
        if (INT_UP[0].firstChild.nodeValue == 'up'):
            sys.exit("Interface " + str(INTERFACE) +
                     " is UP! Terminating without changes")

        if (DEBUGON):
            print("Interface Check OK")
    return ()
Example #17
0
 def discard_changes(self, *args, **kwargs):
     try:
         response = self.m.discard_changes(*args, **kwargs)
         return to_xml(remove_namespaces(response))
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #18
0
 def validate(self, *args, **kwargs):
     try:
         response = self.m.validate(*args, **kwargs)
         return to_xml(remove_namespaces(response))
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #19
0
 def edit_config(self, *args, **kwargs):
     try:
         response = self.m.edit_config(*args, **kwargs)
         return to_xml(remove_namespaces(response))
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #20
0
 def get_config(self, *args, **kwargs):
     try:
         return self.m.get_config(*args, **kwargs).data_xml
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #21
0
 def edit_config(self, *args, **kwargs):
     try:
         self.m.edit_config(*args, **kwargs).data_xml
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #22
0
def execute_nc_action(module, xml_str):
    """ huawei execute-action """

    conn = get_nc_connection(module)
    response = conn.execute_action(xml_str)
    return to_string(to_xml(response))
Example #23
0
 def edit_config(self, *args, **kwargs):
     try:
         response = self.m.edit_config(*args, **kwargs)
         return to_xml(remove_namespaces(response))
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
 def describe_to(self, description):
     description.append_text(to_xml(self.expected, pretty_print=True))
Example #25
0
 def get(self, *args, **kwargs):
     try:
         return self.m.get(*args, **kwargs).data_xml
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))
Example #26
0
 def validate(self, *args, **kwargs):
     try:
         response = self.m.validate(*args, **kwargs)
         return to_xml(remove_namespaces(response))
     except RPCError as exc:
         raise Exception(to_xml(exc.xml))