当前位置: 首页>>代码示例>>Python>>正文


Python Session.get方法代码示例

本文整理汇总了Python中acitoolkit.Session.get方法的典型用法代码示例。如果您正苦于以下问题:Python Session.get方法的具体用法?Python Session.get怎么用?Python Session.get使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在acitoolkit.Session的用法示例。


在下文中一共展示了Session.get方法的6个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: from acitoolkit import Session [as 别名]
# 或者: from acitoolkit.Session import get [as 别名]
def main():
    """
    Main execution routine
    """
    description = ('Simple application that logs on to the APIC'
                   ' and displays usage information for a given DN')
    creds = Credentials('apic', description)
    creds.add_argument("-d", "--dn_name",
                       help="DN to query for usage information")

    args = creds.get()

    session = Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
    url = '/api/mo/{}.json?query-target=children&target-subtree-class=relnFrom'
    url = url.format(args.dn_name)

    resp = session.get(url)

    if resp.ok:
        used_by = resp.json()['imdata']
        for item in used_by:
            kls = next(iter(item))
            attributes = item[kls]['attributes']
            data.append((attributes['tDn'], kls))
    print(tabulate(data, headers=["Used by", "Class"]))
开发者ID:datacenter,项目名称:acitoolkit,代码行数:30,代码来源:aci-where-used.py

示例2: main

# 需要导入模块: from acitoolkit import Session [as 别名]
# 或者: from acitoolkit.Session import get [as 别名]
def main():
    """
    Main execution routine

    :return: None
    """
    # Take login credentials from the command line if provided
    # Otherwise, take them from your environment variables file ~/.profile
    description = 'Simple application that logs on to the APIC and displays all of the Interfaces.'
    creds = Credentials('apic', description)
    creds.add_argument('--tenant', help='The name of Tenant')
    args = creds.get()

    # Login to APIC
    session = Session(args.url, args.login, args.password)
    resp = session.login()
    if not resp.ok:
        print('%% Could not login to APIC')
        sys.exit(0)

    resp = session.get('/api/class/ipv4Addr.json')
    intfs = json.loads(resp.text)['imdata']

    for i in intfs:
        ip = i['ipv4Addr']['attributes']['addr']
        op = i['ipv4Addr']['attributes']['operSt']
        cfg = i['ipv4Addr']['attributes']['operStQual']
        dn = i['ipv4Addr']['attributes']['dn']
        node = dn.split('/')[2]
        intf = re.split(r'\[|\]', dn)[1]
        vrf = re.split(r'/|dom-', dn)[7]
        tn = vrf
        if vrf.find(":") != -1:
            tn = re.search("(.*):(.*)", vrf).group(1)

        check_longest_name(node, "Node")
        check_longest_name(intf, "Interface")
        check_longest_name(ip, "IP Address")
        check_longest_name(cfg, "Admin Status")
        check_longest_name(op, "Status")

        if args.tenant is None:
            if vrf not in data.keys():
                data[vrf] = []
            else:
                data[vrf].append((node, intf, ip, cfg, op))
        else:
            if tn == args.tenant:
                if vrf not in data.keys():
                    data[vrf] = []
                else:
                    data[vrf].append((node, intf, ip, cfg, op))

    for k in data.keys():
        header = 'IP Interface Status for VRF "{}"'.format(k)
        print(header)
        template = '{0:' + str(longest_names["Node"]) + '} ' \
                   '{1:' + str(longest_names["Interface"]) + '} ' \
                   '{2:' + str(longest_names["IP Address"]) + '} ' \
                   '{3:' + str(longest_names["Admin Status"]) + '} ' \
                   '{4:' + str(longest_names["Status"]) + '}'
        print(template.format("Node", "Interface", "IP Address", "Admin Status", "Status"))
        print(template.format('-' * longest_names["Node"],
                              '-' * longest_names["Interface"],
                              '-' * longest_names["IP Address"],
                              '-' * longest_names["Admin Status"],
                              '-' * longest_names["Status"]))
        for rec in sorted(data[k]):
            print(template.format(*rec))
        print('')
开发者ID:datacenter,项目名称:acitoolkit,代码行数:72,代码来源:aci-show-ip-int-brief.py

示例3: InterfaceCollector

# 需要导入模块: from acitoolkit import Session [as 别名]
# 或者: from acitoolkit.Session import get [as 别名]
class InterfaceCollector(object):
    def __init__(self, url, login, password):
        # Login to APIC
        self._apic = Session(url, login, password)
        if not self._apic.login().ok:
            self._logged_in = False
            print '%% Could not login to APIC'
        else:
            self._logged_in = True
        self._interfaces = []
        self._port_channels = []

    def _get_query(self, query_url, error_msg):
        resp = self._apic.get(query_url)
        if not resp.ok:
            print error_msg
            print resp.text
            return []
        return resp.json()['imdata']

    def populate_port_channels(self, node_id, intf_id=None):
        query_url = ('/api/mo/topology/pod-1/node-%s/sys.json?query-target=subtree'
                     '&target-subtree-class=pcAggrIf&rsp-subtree=children&'
                     'rsp-subtree-class=ethpmAggrIf,pcRsMbrIfs' % node_id)
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        port_channels = self._get_query(query_url, error_message)
        if intf_id is None:
            self._port_channels = port_channels
        else:
            self._port_channels = []
            for port_channel in port_channels:
                for if_type in port_channel:
                    if port_channel[if_type]['attributes']['id'] == intf_id:
                        self._port_channels.append(port_channel)

    def populate_interfaces(self, node_id):
        query_url = ('/api/mo/topology/pod-1/node-%s/sys.json?query-target=subtree'
                     '&target-subtree-class=l1PhysIf&rsp-subtree=children&'
                     'rsp-subtree-class=pcAggrMbrIf' % node_id)
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        self._interfaces = self._get_query(query_url, error_message)

    def get_node_ids(self, node_id):
        """
        Get the list of node ids from the command line arguments.
        If none, get all of the node ids
        :param args: Command line arguments
        :return: List of strings containing node ids
        """
        if node_id is not None:
            names = [node_id]
        else:
            names = []
            query_url = ('/api/node/class/fabricNode.json?'
                         'query-target-filter=eq(fabricNode.role,"leaf")')
            error_message = 'Could not get switch list from APIC.'
            nodes = self._get_query(query_url, error_message)
            for node in nodes:
                names.append(str(node['fabricNode']['attributes']['id']))
        return names

    def _get_member_extension(self, port_channel):
        resp = ''
        for child in port_channel['pcAggrIf']['children']:
            if 'pcRsMbrIfs' in child:
                for interface in self._interfaces:
                    if child['pcRsMbrIfs']['attributes']['tDn'] == interface['l1PhysIf']['attributes']['dn']:
                        oper_attr = interface['l1PhysIf']['children'][0]['pcAggrMbrIf']['attributes']
                        if oper_attr['operSt'] == 'module-removed':
                            resp = '(r)'
                        elif oper_attr['operSt'] == 'up':
                            resp = '(P)'
                        elif oper_attr['channelingSt'] == 'individual':
                            resp = "(I)"
                        elif oper_attr['channelingSt'] == 'suspended':
                            resp = "(s)"
                        elif oper_attr['channelingSt'] == 'hot-standby':
                            resp = "(H)"
                        else:
                            resp = "(D)"
                    if resp != '':
                        break
        return resp

    def show_summary(self, node=None, intf_id=None):
        """
        show port-channel summary

        :param node: String containing the specific switch id. If none, all switches are used
        :param intf_id: String containing the specific interface id. If none, all interfaces are used
        :return: None
        """
        for node_id in self.get_node_ids(node):
            self.populate_interfaces(node_id)
            self.populate_port_channels(node_id, intf_id)
            if not len(self._port_channels):
                continue
            print "Switch:", node_id
            print "Flags:  D - Down        P - Up in port-channel (members)"
            print "        I - Individual  H - Hot-standby (LACP only)"
#.........这里部分代码省略.........
开发者ID:amney,项目名称:acitoolkit,代码行数:103,代码来源:aci-show-port-channel-summary.py

示例4: FexCollector

# 需要导入模块: from acitoolkit import Session [as 别名]
# 或者: from acitoolkit.Session import get [as 别名]
class FexCollector(object):
    def __init__(self, url, login, password):
        # Login to APIC
        self._apic = Session(url, login, password)
        if not self._apic.login().ok:
            self._logged_in = False
            print '%% Could not login to APIC'
        else:
            self._logged_in = True

    def _get_query(self, query_url, error_msg):
        resp = self._apic.get(query_url)
        if not resp.ok:
            print error_msg
            print resp.text
            return []
        return resp.json()['imdata']

    def get_fex_attributes(self, node_id, fex_id=None):
        if fex_id is None:
            query_url = ('/api/mo/topology/pod-1/node-%s.json?query-target=subtree'
                         '&target-subtree-class=satmDExtCh' % node_id)
        else:
            query_url = ('/api/mo/topology/pod-1/node-%s.json?query-target=subtree'
                         '&target-subtree-class=satmDExtCh&query-target-filter=eq(satmDExtCh.id, "%s")' % (node_id,
                                                                                                           fex_id))
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        return self._get_query(query_url, error_message)

    def get_fabric_port_attributes(self, node_id, fex_id):
        query_url = ('/api/mo/topology/pod-1/node-%s.json?query-target=subtree'
                     '&target-subtree-class=satmFabP&query-target-filter='
                     'eq(satmFabP.extChId,"%s")' % (node_id, fex_id))
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        return self._get_query(query_url, error_message)

    def get_transceiver_attributes(self, node_id, fab_port_id):
        query_url = ('/api/mo/topology/pod-1/node-%s/sys/satm/fabp-[%s].json?'
                     'query-target=subtree&target-subtree-class=satmRemoteFcot'
                     ',satmRemoteFcotX2' % (node_id, fab_port_id))
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        return self._get_query(query_url, error_message)

    def get_chassis_attributes(self, node_id, fex_id):
        query_url = '/api/mo/topology/pod-1/node-%s/sys/extch-%s.json' % (node_id, fex_id)
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        return self._get_query(query_url, error_message)

    def get_chassis_card_attributes(self, node_id, fex_id):
        query_url = ('/api/mo/topology/pod-1/node-%s/sys/extch-%s.json?'
                    'query-target=subtree&target-subtree-class=eqptExtChCard' % (node_id, fex_id))
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        return self._get_query(query_url, error_message)

    def get_chassis_running_attributes(self, node_id, fex_id):
        query_url = '/api/mo/topology/pod-1/node-%s/sys/extch-%s/running.json' % (node_id, fex_id)
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        return self._get_query(query_url, error_message)

    def get_chassis_cpu_attributes(self, node_id, fex_id):
        query_url = ('/api/mo/topology/pod-1/node-%s/sys/extch-%s.json?'
                    'query-target=subtree&target-subtree-class=eqptExtChCPU' % (node_id, fex_id))
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        return self._get_query(query_url, error_message)

    def get_fex_ids(self, node_id):
        fex_attrs = self.get_fex_attributes(node_id)
        fex_ids = []
        print fex_attrs
        for fex_attr in fex_attrs:
            fex_ids.append(str(fex_attr['satmDExtCh']['attributes']['id']))
        return fex_ids

    def get_node_ids(self, node_id):
        """
        Get the list of node ids from the command line arguments.
        If none, get all of the node ids
        :param args: Command line arguments
        :return: List of strings containing node ids
        """
        if node_id is not None:
            names = [node_id]
        else:
            names = []
            query_url = ('/api/node/class/fabricNode.json?'
                         'query-target-filter=eq(fabricNode.role,"leaf")')
            error_message = 'Could not get switch list from APIC.'
            nodes = self._get_query(query_url, error_message)
            for node in nodes:
                names.append(str(node['fabricNode']['attributes']['id']))
        return names

    @staticmethod
    def print_fex(fex_attr, chassis_attr, detail=False):
        print 'FEX:%s  Description: FEX0%s  state: %s' % (fex_attr['id'],
                                                          fex_attr['id'],
                                                          fex_attr['operSt'])
        print '  FEX version: %s [Switch version: %s]' % (fex_attr['ver'],
                                                          fex_attr['swVer'])

#.........这里部分代码省略.........
开发者ID:amney,项目名称:acitoolkit,代码行数:103,代码来源:aci-show-fex.py

示例5: InterfaceDetailedCollector

# 需要导入模块: from acitoolkit import Session [as 别名]
# 或者: from acitoolkit.Session import get [as 别名]
class InterfaceDetailedCollector(object):
    def __init__(self, url, login, password):
        # Login to APIC
        self._apic = Session(url, login, password)
        if not self._apic.login().ok:
            self._logged_in = False
            print '%% Could not login to APIC'
        else:
            self._logged_in = True
        self._interfaces = []

    def _get_query(self, query_url, error_msg):
        resp = self._apic.get(query_url)
        if not resp.ok:
            print error_msg
            print resp.text
            return []
        return resp.json()['imdata']

    def _populate_beacon_states(self, data):
        for beacon_data in data:
            if 'eqptLocLed' not in beacon_data:
                continue
            dn = beacon_data['eqptLocLed']['attributes']['dn']
            oper_state = beacon_data['eqptLocLed']['attributes']['operSt']
            if 'leafport-' in dn:
                port_num = dn.partition('/leafport-')[2].partition('/')[0]
                mod_num = dn.partition('/lcslot-')[2].partition('/')[0]
                node_num = dn.partition('/node-')[2].partition('/')[0]
                beacon_interface_id = 'eth' + mod_num + '/' + port_num
                beacon_node_id = '/node-%s/' % node_num
                for interface in self._interfaces:
                    if not interface.is_ether():
                        continue
                    if interface.id == beacon_interface_id:
                        if beacon_node_id in dn:
                            interface.beacon_state = oper_state

    def populate_detailed_interfaces(self, node_id, intf_id=None):
        query_url = ('/api/mo/topology/pod-1/node-%s/sys.json?query-target=subtree'
                     '&target-subtree-class=l1PhysIf,pcAggrIf,l3LbRtdIf,tunnelIf,sviIf,l3EncRtdIf,'
                     'mgmtMgmtIf,l2ExtIf,l2VfcIf,eqptLocLed&rsp-subtree=full&'
                     'rsp-subtree-class=ethpmPhysIf,ethpmPortCap,l1RtMbrIfs,ethpmAggrIf,'
                     'rmonEtherStats,rmonIfIn,rmonIfOut,rmonIfStorm,eqptIngrTotal5min,'
                     'eqptEgrTotal5min,l1EeeP,rmonDot3Stats' % node_id)
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        interfaces = self._get_query(query_url, error_message)
        self._interfaces = []
        if intf_id is None:
            for interface in interfaces:
                self._interfaces.append(Interface(interface))
        else:
            for interface in interfaces:
                for if_type in interface:
                    if if_type == 'eqptLocLed':
                        continue
                    if interface[if_type]['attributes']['id'] == intf_id:
                        self._interfaces.append(Interface(interface))
        self._populate_beacon_states(interfaces)


    def get_node_ids(self, node_id):
        """
        Get the list of node ids from the command line arguments.
        If none, get all of the node ids
        :param args: Command line arguments
        :return: List of strings containing node ids
        """
        if node_id is not None:
            names = [node_id]
        else:
            names = []
            query_url = ('/api/node/class/fabricNode.json?'
                         'query-target-filter=eq(fabricNode.role,"leaf")')
            error_message = 'Could not get switch list from APIC.'
            nodes = self._get_query(query_url, error_message)
            for node in nodes:
                names.append(str(node['fabricNode']['attributes']['id']))
        return names

    def show_detailed(self, node=None, intf_id=None):
        """
        show interface

        :param node: String containing the specific switch id. If none, all switches are used
        :param intf_id: String containing the specific interface id. If none, all interfaces are used
        :return: None
        """
        for node_id in self.get_node_ids(node):
            print 'Switch', node_id
            self.populate_detailed_interfaces(node_id, intf_id)
            for interface in self._interfaces:
                if interface.if_type == 'l1PhysIf':
                    if interface.is_ether or interface.is_pc() or interface.is_tun():
                        state = interface.oper_st
                        rsn = interface.oper_st_qual
                        if state is None:
                            state = "unknown"
                            rsn = "unknown"
                        if state == 'link-up':
#.........这里部分代码省略.........
开发者ID:datacenter,项目名称:acitoolkit,代码行数:103,代码来源:aci-show-interface.py

示例6: InterfaceBriefCollector

# 需要导入模块: from acitoolkit import Session [as 别名]
# 或者: from acitoolkit.Session import get [as 别名]
class InterfaceBriefCollector(object):
    def __init__(self, url, login, password):
        # Login to APIC
        self._apic = Session(url, login, password)
        self._if_brief_headers = {
            'l1PhysIf': ['Ethernet Interface', 'VLAN', 'Type', 'Mode', 'Status', 'Reason', 'Speed', 'Port Ch #'],
            'pcAggrIf': ['Port-channel Interface', 'VLAN', 'Type', 'Mode', 'Status', 'Reason', 'Speed', 'Protocol'],
            'l3LbRtdIf': ['Interface', 'Status', 'Description'],
            'tunnelIf': ['Interface', 'Status', 'IP Address', 'Encap type', 'MTU'],
            'sviIf': ['Interface', 'Secondary VLAN(Type)', 'Status', 'Reason'],
            'l3EncRtdIf': [],
            'mgmtMgmtIf': ['Port', 'VRF', 'Status', 'IP Address', 'Speed', 'MTU'],
            'l2ExtIf': [],
            'l2VfcIf': ['Interface', 'Vsan', 'Admin\nMode', 'Admin Trunk Mode', 'Status',
                        'Bind Info', 'Oper Mode', 'Oper Speed (Gbps)']
        }
        self._if_types = self._if_brief_headers.keys()
        if not self._apic.login().ok:
            self._logged_in = False
            print '%% Could not login to APIC'
        else:
            self._logged_in = True
        self._interfaces = []

    @property
    def _all_if_types_as_string(self):
        resp = ''
        for if_type in self._if_types:
            if len(resp):
                resp += ','
            resp += if_type
        return resp

    def _get_query(self, query_url, error_msg):
        resp = self._apic.get(query_url)
        if not resp.ok:
            print error_msg
            print resp.text
            return []
        return resp.json()['imdata']

    def populate_interfaces(self, node_id, intf_id=None):
        query_url = ('/api/mo/topology/pod-1/node-%s/sys.json?query-target=subtree'
                     '&target-subtree-class=%s&rsp-subtree=children&'
                     'rsp-subtree-class=ethpmPhysIf,l1RtMbrIfs,ethpmAggrIf' % (node_id, self._all_if_types_as_string))
        error_message = 'Could not collect APIC data for switch %s.' % node_id
        interfaces = self._get_query(query_url, error_message)
        if intf_id is None:
            self._interfaces = interfaces
        else:
            self._interfaces = []
            for interface in interfaces:
                for if_type in interface:
                    if interface[if_type]['attributes']['id'] == intf_id:
                        self._interfaces.append(interface)

    def _has_interface_type(self, if_type, intf_id=None):
        for interface in self._interfaces:
            if if_type in interface:
                if intf_id is None or intf_id == interface[if_type]['attributes']['id']:
                    return True
        return False

    def _get_interface_type(self, if_type):
        resp = []
        for interface in self._interfaces:
            if if_type in interface:
                resp.append(interface)
        return resp

    def get_node_ids(self, node_id):
        """
        Get the list of node ids from the command line arguments.
        If none, get all of the node ids
        :param args: Command line arguments
        :return: List of strings containing node ids
        """
        if node_id is not None:
            names = [node_id]
        else:
            names = []
            query_url = ('/api/node/class/fabricNode.json?'
                         'query-target-filter=eq(fabricNode.role,"leaf")')
            error_message = 'Could not get switch list from APIC.'
            nodes = self._get_query(query_url, error_message)
            for node in nodes:
                names.append(str(node['fabricNode']['attributes']['id']))
        return names

    @staticmethod
    def convert_to_ascii(data):
        data = str(data).split(',')
        resp = ''
        for letter in data:
            resp += str(unichr(int(letter)))
        return resp

    def _get_interface_type_brief_data(self, if_type, intf_id=None):
        data = []
        for interface in self._interfaces:
#.........这里部分代码省略.........
开发者ID:datacenter,项目名称:acitoolkit,代码行数:103,代码来源:aci-show-interface.py


注:本文中的acitoolkit.Session.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。