├── .gitignore ├── .vscode └── keybindings.json ├── LICENSE ├── NOTICE ├── README.md ├── _config.yml ├── configuration ├── __init__.py ├── create_local_span_session.py └── span_to_server.py ├── deployment5.csv ├── fabric_access ├── __init__.py ├── create_vpc.py └── display_switch_to_leaf_structure.py ├── faults_and_logs ├── __init__.py ├── alleventsbetweendates.py ├── alleventsbetweendates_fulldetail.py ├── most_recent_admin_changes.py ├── most_recent_event_changes.py ├── most_recent_fault_changes.py ├── most_recent_port_down.py └── new_important_faults.py ├── images ├── Menu.JPG ├── add_vlans.JPG ├── fault_summary.JPG ├── fault_summary_example.JPG ├── ipsearch.PNG ├── main_menu.JPG ├── main_menu.PNG ├── operationalepgs.png ├── remove_epgs.JPG ├── show interfaces.JPG ├── shut_notshut.JPG ├── time_example.JPG ├── vlantag.JPG └── vm_poweredoff.PNG ├── information ├── __init__.py ├── bd_epg_relations.py ├── endpoint_per_leaf.py ├── endpoint_search.py ├── routetrace.py ├── routetranslation.py ├── show_static_routes.py ├── switchandapicinfo.py ├── switchandapicinfo.txt ├── top_interface_counters.py ├── top_interface_problems.py └── zoning_rules_checking.py ├── interfaces ├── __init__.py ├── assign_epg_interfaces.py ├── autodeploy.py ├── change_interface_state.py ├── clonevpcanddeploy.py ├── configure_and_deploy.py ├── interfacecounters.py ├── interfacedescriptioncreation.py ├── portchannel_to_phy_interfaces.py ├── portsanddescriptions.py ├── remove_epgs_interfaces.py ├── short_vlan_epg_to_ports.py ├── show_all_endpoints_on_interface.py ├── show_epgs_to_all_interfaces.py ├── show_interface_attributes.py ├── show_interface_epgs.py ├── switch_port_view.py ├── switchpreviewutil.py └── vlan_epg_to_ports.py ├── localutils ├── __init__.py ├── base_classes.py ├── custom_utils.py ├── program_globals.py └── sshleafutil.py ├── main_menu.py ├── misc_unfinished_scripts ├── EPGstoInterfaces.py ├── EPGstoInterfaces.txt ├── EPGstoInterfaces_redesign.py ├── _old_remove_epgs_interfaces.py ├── _old_shut_noshut.py ├── aci_health │ ├── alleventsbetweendates.py │ ├── alleventsbetweendates_fulldetail.py │ ├── most_recent_admin_changes.py │ ├── most_recent_event_changes.py │ ├── most_recent_fault_changes.py │ └── new_important_faults.py ├── apic-python.py ├── endpoint_history2.0.py ├── endpoint_search │ └── ipendpoint_history6.py ├── endpoint_subnet_map.py ├── enpoint_gather.py ├── enpoint_gather_compare.py ├── epg_to_interfaces │ ├── EPGstoInterfaces_redesign2.py │ └── remove_epgs_interfaces.py ├── futureprojects.txt ├── geolocationswitches.py ├── gether_allendpoints_to_interface.py ├── health_reasons.py ├── healthistory.py ├── important_faults - Copy.py ├── important_faults.py ├── interface_information │ ├── interface-egps.py │ └── portsanddescriptions.py ├── ipendpoint_history.py ├── ipendpoint_history3.py ├── ipendpoint_history5_reduce_class.py ├── most_recent_event_changes_no_vmware.py ├── multissh.py ├── path_troubleshooting │ └── routetranslation.py ├── routing.py ├── show_all_endpoints_on_interface.py ├── shut_noshut.py ├── shut_noshut_interfaces.py ├── span_creations │ └── create_local_span_session.py ├── topsystem info.rtf └── urlib.py └── python3_migration ├── configuration ├── __init__.py └── create_local_span_session.py ├── create_local_span_session.py ├── faults_and_logs ├── __init__.py ├── alleventsbetweendates.py ├── alleventsbetweendates_fulldetail.py ├── most_recent_admin_changes.py ├── most_recent_event_changes.py ├── most_recent_fault_changes.py └── new_important_faults.py ├── information ├── __init__.py ├── endpoint_search.py └── routetranslation.py ├── interfaces ├── __init__.py ├── _old_shut_noshut.py ├── assign_epg_interfaces.py ├── change_interface_state.py ├── interfacedescriptioncreation.py ├── portsanddescriptions.py ├── remove_epgs_interfaces.py └── show_interface_epgs.py ├── localutils ├── __init__.py └── custom_utils.py ├── main_menu.py ├── misc_unfinished_scripts ├── EPGstoInterfaces.py ├── EPGstoInterfaces_redesign.py ├── aci_health │ ├── alleventsbetweendates.py │ ├── alleventsbetweendates_fulldetail.py │ ├── most_recent_admin_changes.py │ ├── most_recent_event_changes.py │ ├── most_recent_fault_changes.py │ └── new_important_faults.py ├── apic-python.py ├── endpoint_history2.0.py ├── endpoint_search │ └── ipendpoint_history6.py ├── enpoint_gather.py ├── enpoint_gather_compare.py ├── epg_to_interfaces │ ├── EPGstoInterfaces_redesign2.py │ └── remove_epgs_interfaces.py ├── geolocationswitches.py ├── gether_allendpoints_to_interface.py ├── health_reasons.py ├── healthistory.py ├── important_faults - Copy.py ├── important_faults.py ├── interface_information │ ├── interface-egps.py │ └── portsanddescriptions.py ├── ipendpoint_history.py ├── ipendpoint_history3.py ├── ipendpoint_history5_reduce_class.py ├── path_troubleshooting │ └── routetranslation.py ├── routing.py ├── shut_interfaces │ └── shut_noshut_interfaces.py ├── shut_noshut.py ├── shut_noshut_interfaces.py ├── span_creations │ └── create_local_span_session.py └── urlib.py └── shut_interfaces ├── __init__.py └── remove_epgs_interfaces.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # ACI_Ops 10 | *.log 11 | aciops.log.* 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | .vscode/settings.json 31 | MANIFEST 32 | 33 | # PyInstaller 34 | # Usually these files are written by a python script from a template 35 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 36 | *.manifest 37 | *.spec 38 | 39 | # Installer logs 40 | pip-log.txt 41 | pip-delete-this-directory.txt 42 | 43 | # Unit test / coverage reports 44 | htmlcov/ 45 | .tox/ 46 | .coverage 47 | .coverage.* 48 | .cache 49 | nosetests.xml 50 | coverage.xml 51 | *.cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # logs 60 | aciops.log 61 | aciops.log.* 62 | 63 | # Django stuff: 64 | *.log 65 | local_settings.py 66 | db.sqlite3 67 | 68 | # Flask stuff: 69 | instance/ 70 | .webassets-cache 71 | 72 | # Scrapy stuff: 73 | .scrapy 74 | 75 | # Sphinx documentation 76 | docs/_build/ 77 | 78 | # PyBuilder 79 | target/ 80 | 81 | # Jupyter Notebook 82 | .ipynb_checkpoints 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # celery beat schedule file 88 | celerybeat-schedule 89 | 90 | # SageMath parsed files 91 | *.sage.py 92 | 93 | # Environments 94 | .env 95 | .venv 96 | env/ 97 | venv/ 98 | ENV/ 99 | env.bak/ 100 | venv.bak/ 101 | .vscode 102 | .vscode/ 103 | 104 | # Spyder project settings 105 | .spyderproject 106 | .spyproject 107 | 108 | # Rope project settings 109 | .ropeproject 110 | 111 | # mkdocs documentation 112 | /site 113 | 114 | # mypy 115 | .mypy_cache/ 116 | -------------------------------------------------------------------------------- /.vscode/keybindings.json: -------------------------------------------------------------------------------- 1 | [{ 2 | "key": "shift-f6", 3 | "command": "workbench.action.tasks.echo" 4 | }] -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | ACI_Ops 2 | Copyright (c) 2019 Joshua Settle 3 | 4 | This project includes software developed by Joshua Settle with the assitance of Aaron Warner. 5 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ACI Ops 2 | [![published](https://static.production.devnetcloud.com/codeexchange/assets/images/devnet-published.svg)](https://developer.cisco.com/codeexchange/github/repo/settlej/ACI_Ops) 3 |

4 | Tools to enhance CLI experience replacing slower ACI show commands with additional information. 5 | 6 | WARNING: Sandbox (sandboxapicdc.cisco.com) for APIC doesn't fully work with ACI Ops, this is due to the fact that the APICs and Fabric are virtual and don't have all the API object returns relating to real equipment. 7 | 8 | 9 | Tested in 4.0(3d), 4.1(2m), 4.2(1j), 4.2(3l) APIC 10 | This program fully supports Python2 and will be updated to Python3 when ACI's internal platform migrates from Python2. 11 | 12 | 13 | The entire program uses Python2 Standard Library! 14 | No 3rd party modules to import and update!
15 | Program can run on Windows, Mac, and Linux. 16 | Can be ran on local computer or on APIC itself. 17 | If on the APIC you can store the program in your home directory. 18 |

19 | 20 | # New Features! 21 |

22 | 1.) Picture showing interfaces like available in GUI with colors reflecting interface status, role, errors 23 | 2.) Show recent ports down 24 | 3.) Show all endpoints on interface 25 | 4.) Auto create span to server session 26 | 5.) Option to select EGPs to remove from interfaces 27 | 6.) Option to tag or untag EPGs added to interfaces 28 | 7.) Show all static routes 29 | 8.) Endpoint Search display physical location if endpoint resides on VPC/PC 30 | 9.) Clone access, trunk, or VPC/PC to new interfaces ::Admin state, EPGs (selection possible), Same Leaf selector 31 | 10.) Deploy Access, Trunk, or VPC/PC (EPGs, physical, AEP) in single flow 32 | 11.) Interface Description and EPG update ::CSV 33 | 12.) Show BD > EPG relationships 34 | 13.) Troubleshooting tools 35 |

36 | 37 | # Features in Development! 38 | 1.) Display every contract between EPGs (vrf contracts, Taboo, and Normal EPGs) and filters in detail; in both directions
39 | 40 | # Limitations: 41 |

Python2 42 | Single Pod-1 deployment 43 | Only 1u Leafs supported 44 | Some features like log pull may not be limited to single pod or 1u leaf. 45 |

46 | 47 | # Setup 48 |

49 | No requriments besides python 2.7 and ssh 50 | ACI_Ops can be run on APIC or on local computer 51 | Recommend location on APIC for ACI_Ops: home folder for user 52 | Local computer needs to have "ssh" in cmd or bash to use tools module in ACI_Ops 53 | If running lower than 2.7 ipaddress library will be needed 54 |

55 |

56 | [OPTIONAL] 57 | If you want to run ACI_Ops in a virtualenv for python2. 58 | 59 | (linux) sudo pip install virtualenv 60 | (windows/admin) pip install virtualenv 61 | 62 | python -m virtualenv . 63 | or 64 | python -m virtualenv 65 | 66 | If python2 and python3 on same machine you may need to specify: 67 | python2 -m virtualenv . 68 | cd Scripts
69 | (linux) source activate 70 | (windows) activate 71 |

72 | 73 | # Installation 74 |

git clone https://github.com/settlej/ACI_Ops.git
75 | cd ACI_Ops
76 | python or python2 main_menu.py 77 | 78 | If you want to run on APIC copy all files to the user home directory, via SCP/SFTP. 79 | Then run: python main_menu.py 80 |

81 | 82 | # Enviroment Variables 83 |

If using running ACI_Ops on local computer, for quick login use these three variables: 84 | 1.) apic 85 | 2.) user 86 | 3.) password 87 | apic = [ip/hostname]

88 | 89 | 90 | # Screen Shots: 91 | ![Image of Main Menu](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/Menu.JPG)

92 | # Important Fault Summary 93 | ![Image of fault_summary](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/fault_summary_example.JPG)

94 | # Show vlans per interface 95 | ![Image of vlans](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/operationalepgs.png)
96 | ![Image of vlan2](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/vlantag.JPG)
97 | # Add EPGs to Multiple Interfaces 98 | ![Image of add epgs](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/add_vlans.JPG)

99 | # Remove EPGs from Multiple Interfaces 100 | ![Image of remove_epgs](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/remove_epgs.JPG)

101 | # Better 'show interface status' 102 | ![Image of showinterfaces](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/show%20interfaces.JPG)

103 | # Find Endpoints with Additional Information 104 | ![Image of ip search](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/ipsearch.PNG)

105 | # Find Endpoints even when Powered Off 106 | ![Image of poweroff](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/vm_poweredoff.PNG)

107 | # Gather all logs in timeframe 108 | ![Image of time](https://github.com/settlej/Better_ACI_CLI_Tools/blob/master/images/time_example.JPG) 109 |
Original Auther: Settlej 110 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-cayman -------------------------------------------------------------------------------- /configuration/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/configuration/__init__.py -------------------------------------------------------------------------------- /configuration/create_local_span_session.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | import itertools 14 | import trace 15 | import pdb 16 | import getpass 17 | import datetime 18 | from localutils.custom_utils import * 19 | import interfaces.switchpreviewutil as switchpreviewutil 20 | import logging 21 | 22 | # Create a custom logger 23 | # Allows logging to state detailed info such as module where code is running and 24 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 25 | # grainular logging levels 26 | logger = logging.getLogger('aciops.' + __name__) 27 | 28 | 29 | 30 | def create_span_dest_url(dest_int, name, leaf): 31 | destport = dest_int.dn 32 | spandestgrpname = name + '_leaf' + leaf + '_' + dest_int.name.replace('/','_') 33 | spandestname = name + '_leaf' + leaf + '_' + dest_int.name.replace('/','_') 34 | desturl = """https://{apic}/api/node/mo/uni/infra/destgrp-{}.json""".format(spandestname,apic=apic) 35 | destdata = """{"spanDestGrp":{"attributes":{"name":"%s","status":"created"},"children":[{"spanDest":{"attributes":{"name":"%s","status":"created"},"children":[{"spanRsDestPathEp":{"attributes":{"tDn":"%s","status":"created"},"children":[]}}]}}]}}""" % (spandestgrpname, spandestname, destport) 36 | logger.info(desturl) 37 | logger.info(destdata) 38 | result, error = PostandGetResponseData(desturl, destdata, cookie) 39 | logger.debug(result) 40 | logger.debug(error) 41 | if result == []: 42 | print("Successfully added Destination Port") 43 | return 'Success' 44 | else: 45 | print('\x1b[1;37;41mFailure\x1b[0m -- ' + error) 46 | return 'Failed' 47 | 48 | def create_source_session_and_port(source_int, dest_int, name, leaf): 49 | sourcelist = [] 50 | if len(source_int) >= 1: 51 | for source in source_int: 52 | spansourcename = name + '_leaf' + leaf + '_' + source.name.replace('/','_') 53 | sourcelist.append({"spanSrc":{"attributes":{"name":spansourcename,"status":"created"},"children":[{"spanRsSrcToPathEp":{"attributes":{"tDn":source.dn,"status":"created"},"children":[]}}]}}) 54 | spandestname = name + '_leaf' + leaf + '_'+ dest_int.name.replace('/','_') 55 | spansessionname = name + '_leaf' + leaf + '_' + 'SPAN_SESSION' #+ datetime.datetime.now().strftime('%Y:%m:%dT%H:%M:%S') 56 | #sourceport = source_int.dn 57 | sourceurl = """https://{apic}/api/node/mo/uni/infra/srcgrp-{}.json""".format(spansessionname,apic=apic) 58 | sourcedata = {"spanSrcGrp":{"attributes":{"name":spansessionname,"status":"created"},"children":[{"spanSpanLbl":{"attributes":{"name":spandestname,"status":"created"},"children":[]}}]}} 59 | sourcedata['spanSrcGrp']['children'].extend(sourcelist) 60 | sourcedata = json.dumps(sourcedata) 61 | logger.info(sourceurl) 62 | logger.info(sourcedata) 63 | result, error = PostandGetResponseData(sourceurl, sourcedata, cookie) 64 | logger.debug(result) 65 | logger.debug(error) 66 | if result == []: 67 | print("Successfully added Source Session and Source Port") 68 | else: 69 | print('\x1b[1;37;41mFailure\x1b[0m -- ' + error) 70 | 71 | 72 | def main(import_apic,import_cookie): 73 | global apic 74 | global cookie 75 | cookie = import_cookie 76 | apic = import_apic 77 | while True: 78 | clear_screen() 79 | location_banner('Local SPAN Port Creation Wizard') 80 | 81 | all_leaflist = get_All_leafs(apic,cookie) 82 | if all_leaflist == []: 83 | print('\x1b[1;31;40mFailed to retrieve active leafs, make leafs are operational...\x1b[0m') 84 | custom_raw_input('\n#Press enter to continue...') 85 | return 86 | print("\nWhat is the desired \x1b[1;33;40m'Source and Destination'\x1b[0m leaf for span session?") 87 | print('\r') 88 | time = get_APIC_clock(apic,cookie) 89 | name = time.replace(' ','T') + '_' + getpass.getuser() 90 | chosenleafs = physical_leaf_selection(all_leaflist, apic, cookie) 91 | switchpreviewutil.main(apic,cookie,chosenleafs,purpose='port_status') 92 | direction= 'Source' 93 | print("\nSelect \x1b[1;33;40m{}\x1b[0m interface by number: \n".format(direction)) 94 | source_returnedlist = physical_interface_selection(apic, cookie, chosenleafs, provideleaf=False) 95 | #import pdb; pdb.set_trace() 96 | direction = 'Destination' 97 | print("\nSelect \x1b[1;33;40m{}\x1b[0m interface by number: \n".format(direction)) 98 | dest_returnedlist = physical_interface_selection(apic, cookie, chosenleafs, provideleaf=False) 99 | confirmstr = 'Local SPAN setup:\n Source Port:' 100 | #\x1b[1;33;40m{} {}\x1b[0m '.format(source_returnedlist[0].leaf, source_returnedlist[0].name) 101 | for source in source_returnedlist: 102 | confirmstr += ' \x1b[1;33;40m{} {}\x1b[0m'.format(source.leaf, source.name) 103 | if len(source_returnedlist) > 1 and source_returnedlist[-1] != source: 104 | confirmstr += ',' 105 | for dest in dest_returnedlist: 106 | confirmstr += ' to Destination Port: \x1b[1;33;40m{} {}\x1b[0m '.format(dest.leaf, dest.name) 107 | if len(dest_returnedlist) > 1 and dest_returnedlist[-1] != dest: 108 | confirmstr += ',' 109 | print(confirmstr) 110 | # import pdb; pdb.set_trace() 111 | while True: 112 | ask = custom_raw_input('\nConfirm Local SPAN deployment? [y|n]: ') 113 | if ask != '' and ask[0].lower() == 'y': 114 | break 115 | if ask != '' and ask[0].lower() == 'n': 116 | return 117 | else: 118 | continue 119 | print('\n') 120 | span_dest_result = create_span_dest_url(dest_returnedlist[0], name, chosenleafs[0]) 121 | if span_dest_result == 'Failed': 122 | custom_raw_input("\n\x1b[1;37;41mFailed to created SPAN destination port\x1b[0m. Press enter to continue...") 123 | continue 124 | create_source_session_and_port(source_returnedlist,dest_returnedlist[0], name, chosenleafs[0]) 125 | cookie = refreshToken(apic, cookie) 126 | custom_raw_input('\n#Press enter to continue...') 127 | break 128 | 129 | #if __name__ == '__main__': 130 | # try: 131 | # main() 132 | # except KeyboardInterrupt as k: 133 | # print('\n\nEnding Script....\n') 134 | # exit() 135 | 136 | 137 | #name = custom_raw_input("What is the source interface? ") 138 | # 139 | #name = custom_raw_input(") 140 | # 141 | #{"spanDestGrp":{"attributes":{"dn":"uni/infra/destgrp-SPAN_Destination_eth1_30","name":"SPAN_Destination_eth1_30", 142 | #"rn":"{rn}","status":"created"},"children":[{"spanDest": 143 | #{"attributes":{"dn":"uni/infra/destgrp-SPAN_Destination_eth1_30/dest-SPAN_Destination_eth1_30", 144 | #"name":"SPAN_Destination_eth1_30","rn":"dest-SPAN_Destination_eth1_30","status":"created"}, 145 | #"children":[{"spanRsDestPathEp":{"attributes":{"tDn":"topology/pod-1/paths-101/pathep-[eth1/30]", 146 | #"status":"created"},"children":[]}}]}}]}}.format(dn=dn, name=name, rn=rn, spanDestdn=spanDestdn, spanDestrn=spanDestrn, 147 | #destport=destport) 148 | -------------------------------------------------------------------------------- /deployment5.csv: -------------------------------------------------------------------------------- 1 | 103,eth1/1,auto_1,trunk,immediate,"1,222,3",EPG-VL69-INTERNAL,EPG-VL10-ISE,EPG-VMOTION 2 | 103,eth1/2,auto_2,access,immediate,3,EPG-VMOTION,, 3 | 103,eth1/3,auto_3,access,immediate,5,EPG-S,, 4 | 103,eth1/4,auto_4,trunk,immediate,"1,3",EPG-VL69-INTERNAL,EPG-VMOTION, 5 | 103,eth1/5,auto_5,trunk,immediate,"1,222,3",EPG-VL69-INTERNAL,EPG-VL10-ISE,EPG-VMOTION 6 | 103,eth1/6,auto_6,trunk,immediate,222,EPG-VL10-ISE,, 7 | 103,eth1/7,auto_7,trunk,on-demand,222,EPG-VL10-ISE,, 8 | 103,eth1/8,auto_8,trunk,on-demand,222,EPG-VL10-ISE,, 9 | 103,eth1/9,auto_9,trunk,on-demand,222,EPG-VL10-ISE,, 10 | 103,eth1/10,auto_10,trunk,on-demand,222,EPG-VL10-ISE,, 11 | 101,eth1/11,auto_11,trunk,on-demand,222,EPG-VL10-ISE,, 12 | 101,eth1/12,auto_12,trunk,on-demand,222,EPG-VL10-ISE,, 13 | 101,eth1/13,auto_13,trunk,on-demand,222,EPG-VL10-ISE,, 14 | 101,eth1/14,auto_14,trunk,on-demand,222,EPG-VL10-ISE,, 15 | 101,eth1/15,auto_15,trunk,on-demand,222,EPG-VL10-ISE,, 16 | 101,eth1/16,auto_16,trunk,on-demand,222,EPG-VL10-ISE,, 17 | 101,eth1/17,auto_17,trunk,immediate,222,EPG-VL10-ISE,, 18 | 101,eth1/18,auto_18,trunk,immediate,222,EPG-VL10-ISE,, 19 | 101,eth1/19,auto_19,trunk,immediate,222,EPG-VL10-ISE,, 20 | 101,eth1/20,auto_20,trunk,immediate,222,EPG-VL10-ISE,, 21 | 102,eth1/1,auto_10,trunk,immediate,"1,222,3",EPG-VL69-INTERNAL,EPG-VL10-ISE,EPG-VMOTION 22 | 102,eth1/2,auto_11,access,immediate,3,EPG-VMOTION,, 23 | 102,eth1/3,auto_12,trunk,immediate,5,EPG-S,, 24 | 102,eth1/4,auto_13,trunk,immediate,"1,3",EPG-VL69-INTERNAL,EPG-VMOTION, 25 | 102,eth1/5,auto_14,trunk,immediate,"1,222,3",EPG-VL69-INTERNAL,EPG-VL10-ISE,EPG-VMOTION 26 | 102,eth1/6,auto_15,access,immediate,222,EPG-VL10-ISE,, 27 | 102,eth1/7,auto_16,access,immediate,222,EPG-VL10-ISE,, 28 | 102,eth1/8,auto_17,trunk,immediate,222,EPG-VL10-ISE,, 29 | 102,eth1/9,auto_18,trunk,immediate,222,EPG-VL10-ISE,, 30 | 102,eth1/10,auto_19,trunk,immediate,222,EPG-VL10-ISE,, 31 | 102,eth1/11,auto_20,trunk,immediate,222,EPG-VL10-ISE,, 32 | 102,eth1/12,auto_21,trunk,immediate,222,EPG-VL10-ISE,, 33 | 102,eth1/13,auto_22,trunk,immediate,222,EPG-VL10-ISE,, 34 | 102,eth1/14,auto_23,trunk,immediate,222,EPG-VL10-ISE,, 35 | 102,eth1/15,auto_24,trunk,immediate,222,EPG-VL10-ISE,, 36 | 102,eth1/16,auto_25,trunk,immediate,222,EPG-VL10-ISE,, 37 | 102,eth1/17,auto_26,trunk,immediate,222,EPG-VL10-ISE,, 38 | 102,eth1/18,auto_27,trunk,immediate,222,EPG-VL10-ISE,, 39 | 102,eth1/19,auto_28,trunk,immediate,222,EPG-VL10-ISE,, 40 | 102,eth1/20,auto_29,trunk,immediate,222,EPG-VL10-ISE,, -------------------------------------------------------------------------------- /fabric_access/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/fabric_access/__init__.py -------------------------------------------------------------------------------- /faults_and_logs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/faults_and_logs/__init__.py -------------------------------------------------------------------------------- /faults_and_logs/most_recent_admin_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | from localutils.custom_utils import * 14 | import logging 15 | 16 | # Create a custom logger 17 | # Allows logging to state detailed info such as module where code is running and 18 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 19 | # grainular logging levels 20 | logger = logging.getLogger('aciops.' + __name__) 21 | 22 | def askrefresh(): 23 | while True: 24 | refresh = custom_raw_input("Return to admin list? [y=default|n]: ") or 'y' 25 | if refresh[0].lower() == 'y': 26 | return True 27 | elif refresh[0].lower() == 'n': 28 | return False 29 | else: 30 | continue 31 | 32 | 33 | def gatheranddisplayrecentadmins(): 34 | while True: 35 | clear_screen() 36 | current_time = get_APIC_clock(apic,cookie) 37 | print("Current time = " + current_time) 38 | url = """https://{apic}/api/node/class/aaaModLR.json?query-target-filter=not(wcard(aaaModLR.dn,%22__ui_%22))&order-by=aaaModLR.created|desc&page=0&page-size=50""".format(apic=apic) 39 | logger.info(url) 40 | result = GetResponseData(url, cookie) 41 | print('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','User','admin Summary')) 42 | print('-'*175) 43 | admindict = {} 44 | for num,admin in enumerate(result,1): 45 | if admin.get('aaaModLR'): 46 | admindescr = admin['aaaModLR']['attributes']['descr'].split() 47 | admindescr = ' '.join(admindescr) 48 | if len(admindescr) > 120: 49 | summaryadmindescr = admindescr[:120] + '...' 50 | else: 51 | summaryadmindescr = admindescr 52 | admincreated = ' '.join(admin['aaaModLR']['attributes']['created'].split('T')) 53 | admintrig = admin['aaaModLR']['attributes']['trig'] 54 | adminuser = admin['aaaModLR']['attributes']['user'] 55 | admindn = admin['aaaModLR']['attributes']['dn'] 56 | diff_time = time_difference(current_time,admincreated[:-6]) 57 | admindict[num] = [admincreated[:-6],admintrig,adminuser,admindn,admindescr] 58 | print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,admincreated[:-6],diff_time,admintrig,adminuser,summaryadmindescr)) 59 | 60 | while True: 61 | moredetails = custom_raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 62 | if moredetails == '': 63 | break 64 | if moredetails.isdigit() and admindict.get(int(moredetails)): 65 | break 66 | else: 67 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 68 | if moredetails == '': 69 | continue 70 | diff_time = time_difference(current_time,admindict[int(moredetails)][0]) 71 | print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected')) 72 | print('-'*120) 73 | print('{:26}{:20}{:18}{:18}{}\n'.format(admindict[int(moredetails)][0],diff_time, admindict[int(moredetails)][1],admindict[int(moredetails)][2],'/'.join(str(admindict[int(moredetails)][3]).split('/')[:-1]))) 74 | print('admin Details') 75 | print('-'*15) 76 | print(admindict[int(moredetails)][4]) 77 | print('\n\n') 78 | 79 | refresh = askrefresh() 80 | if refresh == True: 81 | continue 82 | else: 83 | print('\nEnding Program...\n') 84 | break 85 | 86 | 87 | 88 | def main(import_apic,import_cookie): 89 | global apic 90 | global cookie 91 | cookie = import_cookie 92 | apic = import_apic 93 | gatheranddisplayrecentadmins() 94 | 95 | 96 | if __name__ == '__main__': 97 | try: 98 | main() 99 | except KeyboardInterrupt as k: 100 | print("\n\nExiting Program....") 101 | exit() 102 | -------------------------------------------------------------------------------- /faults_and_logs/most_recent_event_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | from localutils.custom_utils import * 14 | import logging 15 | # Create a custom logger 16 | # Allows logging to state detailed info such as module where code is running and 17 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 18 | # grainular logging levels 19 | logger = logging.getLogger('aciops.' + __name__) 20 | 21 | def askrefresh(): 22 | while True: 23 | refresh = custom_raw_input("Return to event list? [y=default|n]: ") or 'y' 24 | if refresh[0].lower() == 'y': 25 | return True 26 | elif refresh[0].lower() == 'n': 27 | return False 28 | else: 29 | continue 30 | 31 | 32 | def gatheranddisplayrecentevents(): 33 | while True: 34 | #getCookie() 35 | clear_screen() 36 | current_time = get_APIC_clock(apic,cookie) 37 | print("Current time = " + current_time) 38 | print("\nEvents loading...\n") 39 | url = """https://{apic}/api/node/class/eventRecord.json?query-target-filter=not(wcard(eventRecord.dn,%22__ui_%22))&order-by=eventRecord.created|desc&page=0&page-size=50""".format(apic=apic) 40 | logger.info(url) 41 | result = GetResponseData(url,cookie,timeout=60) 42 | clear_screen() 43 | print("Current time = " + current_time) 44 | print('\n{:>5} {:26}{:20}{:24}{}'.format('#','Time','Time Difference', 'Port','Event Summary')) 45 | print('-'*175) 46 | eventdict = {} 47 | for num,event in enumerate(result,1): 48 | if event.get('eventRecord'): 49 | eventdescr = event['eventRecord']['attributes']['descr'].split() 50 | eventdescr = ' '.join(eventdescr) 51 | if len(eventdescr) > 120: 52 | summaryeventdescr = eventdescr[:120] + '...' 53 | else: 54 | summaryeventdescr = eventdescr 55 | eventcreated = ' '.join(event['eventRecord']['attributes']['created'].split('T')) 56 | eventtrig = event['eventRecord']['attributes']['trig'] 57 | eventuser = event['eventRecord']['attributes']['user'] 58 | eventdn = event['eventRecord']['attributes']['dn'] 59 | if 'eth' in eventdn and not 'extpaths' in eventdn and not 'span' in eventdn: 60 | leaf = re.search(r'(node-[0-9]{1,3})|(paths-[0-9]{1,3})', eventdn).group() 61 | if leaf.startswith('paths'): 62 | leaf = leaf.replace('paths', 'leaf') 63 | elif leaf.startswith('node'): 64 | leaf = leaf.replace('node', 'leaf') 65 | interface = re.search(r'eth.*\/[0-9]{1,3}\]', eventdn).group() 66 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 67 | elif re.search(r'po[0-9]*\]', eventdn): 68 | leaf = re.search(r'node-[0-9]{1,3}', eventdn).group() 69 | leaf = leaf.replace('node', 'leaf') 70 | interface = re.search(r'po[0-9]*\]', eventdn).group() 71 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 72 | #elif 'rsoosPath' in eventdn and not 'extpaths' in eventdn: 73 | # leaf = re.search(r'protpaths-[0-9]{3}-[0-9]{3}', eventdn).group() 74 | # leaf = leaf.replace('protpaths', 'VPC node') 75 | # interface = re.search(r'pathep-.*\]', eventdn).group() 76 | # interface = interface.replace('pathep-', "") 77 | # portinterfaces = '{} {}'.format(leaf,interface[:-1]) 78 | #elif 'rsoosPath' in eventdn and 'extpaths' in eventdn: 79 | # leaf = re.search(r'paths-[0-9]{3}', eventdn).group() 80 | # leaf = leaf.replace('paths','node') 81 | # fex = re.search(r'extpaths-.*\]', eventdn).group() 82 | # interface = re.search(r'eth[0-9]{1,3}/[0-9]{1,3}', eventdn).group() 83 | # portinterfaces = '{} {} {}'.format(leaf,fex,interface) 84 | else: 85 | portinterfaces = "" 86 | diff_time = time_difference(current_time,eventcreated[:-6]) 87 | eventdict[num] = [eventcreated[:-6],eventtrig,eventuser,eventdn,eventdescr] 88 | print('{:5}.) {:26}{:20}{:24}{}'.format(num,eventcreated[:-6],diff_time,portinterfaces,summaryeventdescr)) 89 | 90 | while True: 91 | moredetails = custom_raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 92 | if moredetails == '': 93 | break 94 | if moredetails.isdigit() and eventdict.get(int(moredetails)): 95 | break 96 | else: 97 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 98 | if moredetails == '': 99 | continue 100 | diff_time = time_difference(current_time,eventdict[int(moredetails)][0]) 101 | print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected')) 102 | print('-'*120) 103 | print('{:26}{:20}{:18}{:18}{}\n'.format(eventdict[int(moredetails)][0],diff_time, eventdict[int(moredetails)][1],eventdict[int(moredetails)][2],'/'.join(str(eventdict[int(moredetails)][3]).split('/')[:-1]))) 104 | print('Event Details') 105 | print('-'*15) 106 | print(eventdict[int(moredetails)][4]) 107 | print('\n\n') 108 | refresh = askrefresh() 109 | if refresh == True: 110 | continue 111 | else: 112 | print('\nEnding Program...\n') 113 | break 114 | 115 | 116 | def main(import_apic,import_cookie): 117 | global apic 118 | global cookie 119 | cookie = import_cookie 120 | apic = import_apic 121 | gatheranddisplayrecentevents() 122 | 123 | 124 | if __name__ == '__main__': 125 | try: 126 | main() 127 | except KeyboardInterrupt as k: 128 | print("\n\nExiting Program....") 129 | exit() 130 | -------------------------------------------------------------------------------- /faults_and_logs/most_recent_fault_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | from localutils.custom_utils import * 14 | import logging 15 | 16 | # Create a custom logger 17 | # Allows logging to state detailed info such as module where code is running and 18 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 19 | # grainular logging levels 20 | logger = logging.getLogger('aciops.' + __name__) 21 | 22 | def askrefresh(): 23 | while True: 24 | refresh = custom_raw_input("Return to fault list? [y=default|n]: ") or 'y' 25 | if refresh[0].lower() == 'y': 26 | return True 27 | elif refresh[0].lower() == 'n': 28 | return False 29 | else: 30 | continue 31 | 32 | def gatheranddisplayrecentfaults(): 33 | while True: 34 | clear_screen() 35 | current_time = get_APIC_clock(apic,cookie) 36 | print("Current time = " + current_time) 37 | url = """https://{apic}/api/node/class/faultInfo.json?query-target-filter=and(ne(faultInfo.severity,"cleared"))&order-by=faultInfo.lastTransition|desc&page=0&page-size=100""".format(apic=apic) 38 | logger.info(url) 39 | result = GetResponseData(url,cookie,timeout=60) 40 | print('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','Fault-State','Fault Summary')) 41 | print('-'*175) 42 | faultdict = {} 43 | for num,fault in enumerate(result,1): 44 | if fault.get('faultInst'): 45 | faultdescr = fault['faultInst']['attributes']['descr'].split() 46 | faultdescr = ' '.join(faultdescr) 47 | if len(faultdescr) > 120: 48 | summaryfaultdescr = faultdescr[:112] + '...' 49 | else: 50 | summaryfaultdescr = faultdescr 51 | faultlastTransition = ' '.join(fault['faultInst']['attributes']['lastTransition'].split('T')) 52 | faulttype = fault['faultInst']['attributes']['type'] 53 | faultstate = fault['faultInst']['attributes']['lc'] 54 | faultdn = fault['faultInst']['attributes']['dn'] 55 | diff_time = time_difference(current_time, faultlastTransition[:-6]) 56 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 57 | print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 58 | else: 59 | faultdescr = fault['faultDelegate']['attributes']['descr'].split() 60 | faultdescr = ' '.join(faultdescr) 61 | if len(faultdescr) > 120: 62 | summaryfaultdescr = faultdescr[:112] + '...' 63 | else: 64 | summaryfaultdescr = faultdescr 65 | faultlastTransition = ' '.join(fault['faultDelegate']['attributes']['lastTransition'].split('T')) 66 | faulttype = fault['faultDelegate']['attributes']['type'] 67 | faultstate = fault['faultDelegate']['attributes']['lc'] 68 | faultdn = fault['faultDelegate']['attributes']['dn'] 69 | diff_time = time_difference(current_time, faultlastTransition[:-6]) 70 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 71 | print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 72 | while True: 73 | moredetails = custom_raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 74 | if moredetails == '': 75 | break 76 | if moredetails.isdigit() and faultdict.get(int(moredetails)): 77 | break 78 | else: 79 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 80 | if moredetails == '': 81 | continue 82 | diff_time = time_difference(current_time, faultdict[int(moredetails)][0]) 83 | print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','Fault-State','Object-Affected')) 84 | print('-'*120) 85 | print('{:26}{:20}{:18}{:18}{}\n'.format(faultdict[int(moredetails)][0],diff_time, faultdict[int(moredetails)][1],faultdict[int(moredetails)][2],'/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1]))) 86 | print('Fault Details') 87 | print('-'*15) 88 | print(faultdict[int(moredetails)][4]) 89 | print('\n\n') 90 | refresh = askrefresh() 91 | if refresh == True: 92 | continue 93 | else: 94 | print('\nEnding Program...\n') 95 | break 96 | 97 | 98 | def main(import_apic,import_cookie): 99 | global apic 100 | global cookie 101 | cookie = import_cookie 102 | apic = import_apic 103 | gatheranddisplayrecentfaults() 104 | 105 | 106 | if __name__ == '__main__': 107 | try: 108 | main() 109 | except KeyboardInterrupt as k: 110 | print("\n\nExiting Program....") 111 | exit() 112 | -------------------------------------------------------------------------------- /faults_and_logs/most_recent_port_down.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | from localutils.custom_utils import * 14 | import logging 15 | 16 | # Create a custom logger 17 | # Allows logging to state detailed info such as module where code is running and 18 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 19 | # grainular logging levels 20 | logger = logging.getLogger('aciops.' + __name__) 21 | 22 | 23 | def askrefresh(): 24 | while True: 25 | refresh = custom_raw_input("Return to event list? [y=default|n]: ") or 'y' 26 | if refresh[0].lower() == 'y': 27 | return True 28 | elif refresh[0].lower() == 'n': 29 | return False 30 | else: 31 | continue 32 | 33 | 34 | def gatheranddisplayrecentevents(): 35 | while True: 36 | #getCookie() 37 | clear_screen() 38 | current_time = get_APIC_clock(apic,cookie) 39 | print("Current time = " + current_time) 40 | print("\nEvents loading...\n") 41 | url = """https://{apic}/api/node/class/eventRecord.json?query-target-filter=or(eq(eventRecord.cause,"port-up"),eq(eventRecord.cause,"port-down"),eq(eventRecord.cause,"port-pfc-congested"),eq(eventRecord.cause,"port-security-config-not-supported"),eq(eventRecord.cause,"update-remote-port-to-dbgrelem-failed"),eq(eventRecord.cause,"addor-del-uplink-port-group-failed"),eq(eventRecord.cause,"addor-del-vtep-port-group-failed"),eq(eventRecord.cause,"port-state-change"),eq(eventRecord.cause,"port-pfc-congested"))&order-by=eventRecord.created|desc&page=0&page-size=100""".format(apic=apic) 42 | logger.info(url) 43 | result = GetResponseData(url,cookie,timeout=60) 44 | clear_screen() 45 | print("Current time = " + current_time) 46 | print('\n{:>5} {:26}{:20}{:24}{}'.format('#','Time','Time Difference', 'Port','Event Summary')) 47 | print('-'*100) 48 | eventdict = {} 49 | for num,event in enumerate(result,1): 50 | if event.get('eventRecord'): 51 | eventdescr = event['eventRecord']['attributes']['descr'].split() 52 | eventdescr = ' '.join(eventdescr) 53 | if len(eventdescr) > 120: 54 | summaryeventdescr = eventdescr[:120] + '...' 55 | else: 56 | summaryeventdescr = eventdescr 57 | eventcreated = ' '.join(event['eventRecord']['attributes']['created'].split('T')) 58 | eventtrig = event['eventRecord']['attributes']['trig'] 59 | eventuser = event['eventRecord']['attributes']['user'] 60 | eventdn = event['eventRecord']['attributes']['dn'] 61 | eventcode = event['eventRecord']['attributes']['code'] 62 | eventchangeset = event['eventRecord']['attributes']['changeSet'] 63 | if 'eth' in eventdn and not 'extpaths' in eventdn: 64 | leaf = re.search(r'(node-[0-9]{1,3})|(paths-[0-9]{1,3})', eventdn).group() 65 | if leaf.startswith('paths'): 66 | leaf = leaf.replace('paths', 'leaf') 67 | elif leaf.startswith('node'): 68 | leaf = leaf.replace('node', 'leaf') 69 | interface = re.search(r'eth.*\/[0-9]{1,3}\]', eventdn).group() 70 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 71 | elif re.search(r'po[0-9]*\]', eventdn): 72 | leaf = re.search(r'node-[0-9]{1,3}', eventdn).group() 73 | leaf = leaf.replace('node', 'leaf') 74 | interface = re.search(r'po[0-9]*\]', eventdn).group() 75 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 76 | #elif 'rsoosPath' in eventdn and not 'extpaths' in eventdn: 77 | # leaf = re.search(r'protpaths-[0-9]{3}-[0-9]{3}', eventdn).group() 78 | # leaf = leaf.replace('protpaths', 'VPC node') 79 | # interface = re.search(r'pathep-.*\]', eventdn).group() 80 | # interface = interface.replace('pathep-', "") 81 | # portinterfaces = '{} {}'.format(leaf,interface[:-1]) 82 | #elif 'rsoosPath' in eventdn and 'extpaths' in eventdn: 83 | # leaf = re.search(r'paths-[0-9]{3}', eventdn).group() 84 | # leaf = leaf.replace('paths','node') 85 | # fex = re.search(r'extpaths-.*\]', eventdn).group() 86 | # interface = re.search(r'eth[0-9]{1,3}/[0-9]{1,3}', eventdn).group() 87 | # portinterfaces = '{} {} {}'.format(leaf,fex,interface) 88 | else: 89 | portinterfaces = "" 90 | diff_time = time_difference(current_time,eventcreated[:-6]) 91 | eventdict[num] = [eventcreated[:-6],eventcode,eventuser,eventdn,eventdescr,eventchangeset] 92 | print('{:5}.) {:26}{:20}{:24}{}'.format(num,eventcreated[:-6],diff_time,portinterfaces,summaryeventdescr)) 93 | while True: 94 | refresh = False 95 | while True: 96 | moredetails = custom_raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 97 | if moredetails == '': 98 | break 99 | if moredetails.isdigit() and eventdict.get(int(moredetails)): 100 | break 101 | else: 102 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 103 | if moredetails == '': 104 | refresh = True 105 | if refresh: 106 | break 107 | diff_time = time_difference(current_time,eventdict[int(moredetails)][0]) 108 | print('\n\n{:26}{:20}{:18}{:18}{}\n'.format('Time','Time Difference', 'Code','User','Object-Affected')) 109 | print('-'*120) 110 | print('{:26}{:20}{:18}{:18}{}'.format(eventdict[int(moredetails)][0],diff_time, eventdict[int(moredetails)][1],eventdict[int(moredetails)][2],'/'.join(str(eventdict[int(moredetails)][3]).split('/')[:-1]))) 111 | print('') 112 | print('Event Details') 113 | print('-'*15) 114 | print(eventdict[int(moredetails)][4]) 115 | print('') 116 | print('Event ChangeSet') 117 | print('-'*15) 118 | print(eventdict[int(moredetails)][5]) 119 | print('\n') 120 | #refresh = askrefresh() 121 | #if refresh == True: 122 | # continue 123 | #else: 124 | # print('\nEnding Program...\n') 125 | # break 126 | refresh = False 127 | 128 | 129 | def main(import_apic,import_cookie): 130 | global apic 131 | global cookie 132 | cookie = import_cookie 133 | apic = import_apic 134 | gatheranddisplayrecentevents() 135 | 136 | 137 | if __name__ == '__main__': 138 | try: 139 | main() 140 | except KeyboardInterrupt as k: 141 | print("\n\nExiting Program....") 142 | exit() 143 | -------------------------------------------------------------------------------- /images/Menu.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/Menu.JPG -------------------------------------------------------------------------------- /images/add_vlans.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/add_vlans.JPG -------------------------------------------------------------------------------- /images/fault_summary.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/fault_summary.JPG -------------------------------------------------------------------------------- /images/fault_summary_example.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/fault_summary_example.JPG -------------------------------------------------------------------------------- /images/ipsearch.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/ipsearch.PNG -------------------------------------------------------------------------------- /images/main_menu.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/main_menu.JPG -------------------------------------------------------------------------------- /images/main_menu.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/main_menu.PNG -------------------------------------------------------------------------------- /images/operationalepgs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/operationalepgs.png -------------------------------------------------------------------------------- /images/remove_epgs.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/remove_epgs.JPG -------------------------------------------------------------------------------- /images/show interfaces.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/show interfaces.JPG -------------------------------------------------------------------------------- /images/shut_notshut.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/shut_notshut.JPG -------------------------------------------------------------------------------- /images/time_example.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/time_example.JPG -------------------------------------------------------------------------------- /images/vlantag.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/vlantag.JPG -------------------------------------------------------------------------------- /images/vm_poweredoff.PNG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/images/vm_poweredoff.PNG -------------------------------------------------------------------------------- /information/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/information/__init__.py -------------------------------------------------------------------------------- /information/bd_epg_relations.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import trace 12 | import logging 13 | import os 14 | import time 15 | import itertools 16 | import threading 17 | import Queue 18 | import interfaces.switchpreviewutil as switchpreviewutil 19 | from localutils.custom_utils import * 20 | import logging 21 | 22 | # Create a custom logger 23 | # Allows logging to state detailed info such as module where code is running and 24 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 25 | # grainular logging levels 26 | logger = logging.getLogger('aciops.' + __name__) 27 | 28 | class fvEPG(): 29 | def __init__(self, epg): 30 | _,t,a,e = epg.split('/') 31 | self.tenant = t 32 | self.app = a 33 | self.epg = e 34 | 35 | class fvBD(): 36 | def __init__(self, bd): 37 | self.tenant = bd.split('/')[1].replace('tn-','') 38 | self.bd = bd.split('/')[2].replace('BD-','',1) 39 | self.epglist = [] 40 | def add_epg(self, epg): 41 | self.epglist.append(epg) 42 | def sort_epgs(self): 43 | self.epglist.sort(key=lambda x: (x.tenant.lower(),x.app.lower(),x.epg.lower())) 44 | def __repr__(self): 45 | if self.epglist == []: 46 | return "BD-{}_EPGs-[None]".format(self.bd) 47 | else: 48 | return "BD-{}_EPGs-{}".format(self.bd,self.epglist) 49 | 50 | def gather_bd_and_epg(apic, cookie): 51 | url = """https://{apic}/api/node/class/fvBD.json?rsp-subtree=children&rsp-subtree-class=fvRtBd""".format(apic=apic) 52 | result = GetResponseData(url, cookie) 53 | return result 54 | 55 | def catigorize_bd_to_epg(bd_tree): 56 | bdlist = [] 57 | for bd in bd_tree: 58 | bdobj = fvBD(bd['fvBD']['attributes']['dn']) 59 | if bd['fvBD'].get('children'): 60 | for epg in bd['fvBD']['children']: 61 | bdobj.add_epg(fvEPG(epg['fvRtBd']['attributes']['tDn'])) 62 | bdobj.sort_epgs() 63 | bdlist.append(bdobj) 64 | return bdlist 65 | 66 | def main(apic, cookie): 67 | clear_screen() 68 | location_banner('BD to EPG Relationships') 69 | bd_tree = gather_bd_and_epg(apic,cookie) 70 | bd_epg_objlist = catigorize_bd_to_epg(bd_tree) 71 | layoutlist = [] 72 | for bdobj in sorted(bd_epg_objlist, key=lambda x: (x.tenant.lower(), x.bd.lower())): 73 | #print(bdobj) 74 | if bdobj.epglist == []: 75 | #if not currenttenant == bdobj.tenant: 76 | # print('-'* 75) 77 | # currenttenant = bdobj.tenant 78 | layoutlist.append((bdobj.tenant,bdobj.bd,'')) 79 | else: 80 | #if not currenttenant == bdobj.tenant: 81 | # print('-' * 75) 82 | # currenttenant = bdobj.tenant 83 | layoutlist.append((bdobj.tenant, bdobj.bd, ('/'.join((bdobj.epglist[0].tenant,bdobj.epglist[0].app,bdobj.epglist[0].epg))).replace('tn-','').replace('ap-','').replace('epg-',''))) 84 | # print('{:20} {:25} {}|{}|{}'.format(bdobj.tenant, bdobj.bd, bdobj.epglist[0].tenant,bdobj.epglist[0].app,bdobj.epglist[0].epg)) 85 | if len(bdobj.epglist) > 1: 86 | # if not currenttenant == bdobj.tenant: 87 | # print('-' * 75) 88 | # currenttenant = bdobj.tenant 89 | for epg in bdobj.epglist[1:]: 90 | layoutlist.append(('','',('/'.join((epg.tenant,epg.app,epg.epg))).replace('tn-','').replace('ap-','').replace('epg-',''))) 91 | # print('{:20} {:25} {}|{}|{}'.format('','',epg.tenant,epg.app,epg.epg)) 92 | currenttenant = None 93 | #import pdb; pdb.set_trace() 94 | topstringheaders = ('Tenant','Bridge Domain','Tenant/App/EPG') 95 | sizes = get_column_sizes(layoutlist, minimum=5,baseminimum=topstringheaders) 96 | print(' \x1b[1;33;40m{:{tenant}} | {:{bd}} | {:{tae}}\x1b[0m'.format('Tenant','Bridge Domain','Tenant/App/EPG',tenant=sizes[0],bd=sizes[1],tae=sizes[2])) 97 | for row in layoutlist: 98 | if not currenttenant == row[0] and row[0] != '': 99 | print(' ' + '-' * (sum(sizes) + 6)) 100 | currenttenant = row[0] 101 | print(' {:{tenant}} | {:{bd}} | {:{epg}}'.format(*row,tenant=sizes[0],bd=sizes[1],epg=sizes[2])) 102 | #print(bdobj.bd, bdobj.epglist) 103 | #import pdb; pdb.set_trace() 104 | custom_raw_input('\nContinue...') -------------------------------------------------------------------------------- /information/switchandapicinfo.txt: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | import itertools 14 | #import trace 15 | #import pdb 16 | import random 17 | import threading 18 | import Queue 19 | from collections import namedtuple 20 | import interfaces.switchpreviewutil as switchpreviewutil 21 | from localutils.custom_utils import * 22 | import logging 23 | 24 | # Create a custom logger 25 | # Allows logging to state detailed info such as module where code is running and 26 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 27 | # grainular logging levels 28 | logger = logging.getLogger('aciops.' + __name__) 29 | logger.setLevel(logging.INFO) 30 | 31 | # Define logging handler for file and console logging. Console logging can be desplayed during 32 | # program run time, similar to print. Program can display or write to log file if more debug 33 | # info needed. DEBUG is lowest and will display all logging messages in program. 34 | c_handler = logging.StreamHandler() 35 | f_handler = logging.FileHandler('aciops.log') 36 | c_handler.setLevel(logging.CRITICAL) 37 | f_handler.setLevel(logging.DEBUG) 38 | 39 | # Create formatters and add it to handlers. This creates custom logging format such as timestamp, 40 | # module running, function, debug level, and custom text info (message) like print. 41 | c_format = logging.Formatter('%(name)s - %(levelname)s - %(message)s') 42 | f_format = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(funcName)s - %(message)s') 43 | c_handler.setFormatter(c_format) 44 | f_handler.setFormatter(f_format) 45 | 46 | # Add handlers to the parent custom logger 47 | logger.addHandler(c_handler) 48 | logger.addHandler(f_handler) 49 | 50 | url = https://192.168.255.2/api/node/class/topSystem.json 51 | result = Get -------------------------------------------------------------------------------- /interfaces/__init__.py: -------------------------------------------------------------------------------- 1 | #from localutils.custom_utils import * -------------------------------------------------------------------------------- /interfaces/interfacedescriptioncreation.py: -------------------------------------------------------------------------------- 1 | 2 | def createinterfacedescr(overrideName, description, interface) 3 | url = https://localhost/api/node/mo/uni/infra/hpaths-{overrideName}.json.format(overrideName=overrideName) 4 | payload{"infraHPathS":{"attributes":{"name":"%(overrideName)s","status":"created,modified","descr":"%(description)s"},"children":[{"infraRsHPathAtt":{"attributes":{"tDn":"%(interface)s"},"children":[]}}]}} 5 | response: {"totalCount":"0","imdata":[]} -------------------------------------------------------------------------------- /interfaces/portchannel_to_phy_interfaces.py: -------------------------------------------------------------------------------- 1 | import re 2 | try: 3 | import readline 4 | except: 5 | pass 6 | import urllib2 7 | import json 8 | import ssl 9 | import os 10 | import datetime 11 | import itertools 12 | #import trace 13 | #import pdb 14 | import random 15 | import threading 16 | import Queue 17 | from collections import namedtuple 18 | import interfaces.switchpreviewutil as switchpreviewutil 19 | from localutils.custom_utils import * 20 | import logging 21 | 22 | # Create a custom logger 23 | # Allows logging to state detailed info such as module where code is running and 24 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 25 | # grainular logging levels 26 | logger = logging.getLogger('aciops.' + __name__) 27 | 28 | def local_interface_menu(): 29 | while True: 30 | print("\nSelect type of interface(s): \n\n" + \ 31 | "\t1.) PC Interfaces: \n" + \ 32 | "\t2.) VPC Interfaces: \n") 33 | selection = custom_raw_input("Select number: ") 34 | print('\r') 35 | if selection.isdigit() and selection != '' and 1 <= int(selection) <= 3: 36 | break 37 | else: 38 | continue 39 | return selection 40 | 41 | class pcAggrIf(): 42 | def __init__(self, **kwargs): 43 | self.__dict__.update(kwargs) 44 | 45 | 46 | def main(import_apic,import_cookie): 47 | while True: 48 | global apic 49 | global cookie 50 | cookie = import_cookie 51 | apic = import_apic 52 | allpclist = get_All_PCs(apic,cookie) 53 | allvpclist = get_All_vPCs(apic,cookie) 54 | clear_screen() 55 | location_banner('Show port-channel locations') 56 | 57 | selection = local_interface_menu() 58 | if selection == '1': 59 | interfacelist = port_channel_selection(allpclist) 60 | all_locations = port_channel_location(interfacelist[0].name,apic,cookie) 61 | print("{}".format('\nPort-Channel Location:')) 62 | print('{}'.format('-'*22)) 63 | for locations in sorted(all_locations): 64 | print(" \x1b[1;33;40m{} : {}\x1b[0m".format(', '.join(locations[:1]), ', '.join(locations[1]))) 65 | 66 | custom_raw_input('\nPress Enter to Coninue...') 67 | elif selection == '2': 68 | interfacelist = port_channel_selection(allvpclist) 69 | all_locations = port_channel_location(interfacelist[0].name,apic,cookie) 70 | print(" {}".format('\nPort-Channel Location:')) 71 | print('{}'.format('-'*22)) 72 | for locations in sorted(all_locations): 73 | print(" \x1b[1;33;40m{} : {}\x1b[0m".format(', '.join(locations[:1]), ', '.join(locations[1]))) 74 | custom_raw_input('\nPress Enter to Coninue...') 75 | 76 | #import pdb; pdb.set_trace() 77 | 78 | 79 | 80 | #url = """https://{apic}/api/class/pcAggrIf.json?query-target-filter=eq(pcAggrIf.name,"{pcname}")&rsp-subtree=full&rsp-subtree-class=pcRsMbrIfs""" -------------------------------------------------------------------------------- /interfaces/show_interface_epgs.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | #import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib2 9 | import json 10 | import ssl 11 | import os 12 | from localutils.custom_utils import * 13 | import logging 14 | 15 | # Create a custom logger 16 | # Allows logging to state detailed info such as module where code is running and 17 | # specifiy logging levels for file vs console. Set default level to DEBUG to allow more 18 | # grainular logging levels 19 | logger = logging.getLogger('aciops.' + __name__) 20 | 21 | def retrieve_leaf_list(): 22 | # Display available leafs beginning of script 23 | url = """https://localhost/api/node/mo/topology/pod-1.json?query-target=children&target-subtree-class=fabricNode&query-target-filter=and(wcard(fabricNode.id,"^1[0-9][0-9]"))""" 24 | logger.info(url) 25 | result = GetResponseData(url,cookie) 26 | #print(result) 27 | leafs = [leaf['fabricNode']['attributes']['id'] for leaf in result] 28 | #print('Available leafs to bounce ports...') 29 | return leafs 30 | 31 | def displayepgs(result): 32 | print('\n{:10}{:15}{}'.format('Tenant','APP','EPG')) 33 | print('-'*40) 34 | #print(result) 35 | if result[0]['l1PhysIf']['attributes']['layer'] == 'Layer3': 36 | print('Layer 3 interface, no EPGs\n') 37 | return 38 | if result[0]['l1PhysIf'].get('children'): 39 | for int in result[0]['l1PhysIf']['children']: 40 | for epgs in int['pconsCtrlrDeployCtx']['children']: 41 | epgpath = epgs['pconsResourceCtx']['attributes']['ctxDn'].split('/') 42 | #print(epgpath) 43 | tenant = epgpath[1][3:] 44 | app = epgpath[2][3:] 45 | epg = epgpath[3][4:] 46 | print('{:10}{:15}{}'.format(tenant,app,epg)) 47 | print('\n') 48 | else: 49 | print('No Epgs found...\n') 50 | 51 | def gatherandstoreinterfacesforleaf(leaf): 52 | url = """https://localhost/api/node/class/topology/pod-1/node-101/l1PhysIf.json""" 53 | logger.info(url) 54 | result = GetResponseData(url,cookie) 55 | listofinterfaces = [interface['l1PhysIf']['attributes']['id'] for interface in result] 56 | return listofinterfaces 57 | 58 | def main(import_apic,import_cookie): 59 | global apic 60 | global cookie 61 | cookie = import_cookie 62 | apic = import_apic 63 | fex = False 64 | clear_screen() 65 | print("\n1.) Physical interface\n" + 66 | "2.) Port-channel/vPC\n") 67 | int_type = raw_input("What is the interface type?: ") 68 | if int_type == '1': 69 | listleafs = retrieve_leaf_list() 70 | print('\nAvailable Leafs\n' + '-'*12) 71 | for leaf in sorted(listleafs): 72 | print(leaf)#Leaf' + ' Leaf'.join(leafs)) 73 | print('\r') 74 | while True: 75 | leaf = raw_input("What is leaf number?: ") 76 | if leaf in listleafs: 77 | break 78 | else: 79 | print('\x1b[41;1mInvalid or leaf does not exist...try again\x1b[0m\n') 80 | availableinterfaces = gatherandstoreinterfacesforleaf(leaf) 81 | while True: 82 | if fex == True: 83 | interface = raw_input("What is the interface? (format: ethxxx/x/x): ") 84 | else: 85 | interface = raw_input("What is the interface? (format: ethx/x): ") 86 | if interface in availableinterfaces: 87 | break 88 | else: 89 | print('\x1b[41;1mInvalid or interface does not exist...try again\x1b[0m\n') 90 | 91 | url = """https://localhost/api/node/mo/topology/pod-1/node-{leaf}/sys/phys-[{interface}].json?rsp-subtree-include=full-deployment&target-node=all&target-path=l1EthIfToEPg""".format(leaf=leaf,interface=interface) 92 | logger.info(url) 93 | result = GetResponseData(url,cookie) 94 | displayepgs(result) 95 | elif int_type == 2: 96 | pass 97 | else: 98 | pass 99 | 100 | 101 | 102 | 103 | -------------------------------------------------------------------------------- /localutils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/localutils/__init__.py -------------------------------------------------------------------------------- /localutils/base_classes.py: -------------------------------------------------------------------------------- 1 | import re 2 | #from localutils.custom_utils import * 3 | import itertools 4 | class interfacebase(): 5 | def get_leaf(self, x): 6 | leafcompile = re.compile(r"((node-|paths-)\d+)") 7 | if leafcompile.search(x): 8 | return leafcompile.search(x).group(1) 9 | else: 10 | return None 11 | def get_pod(self, x): 12 | podcompile = re.compile(r"pod-\d+") 13 | if podcompile.search(x): 14 | return podcompile.search(x).group() 15 | else: 16 | return None 17 | def get_leaf_num(self, x): 18 | result = self.getleaf(x) 19 | if result: 20 | return re.search(r'\d+',result).group() 21 | else: 22 | return None 23 | def get_pod_num(self, x): 24 | result = self.getpod(x) 25 | if result: 26 | return re.search(r'\d+',result).group() 27 | else: 28 | return None 29 | def get_pc_name(self, x): 30 | pccompile = re.compile(r"accbundle-([^/]*)") 31 | if pccompile.search(x): 32 | return pccompile.group(1) 33 | else: 34 | return None 35 | def get_pc_num(self, x, num_only=False): 36 | if num_only: 37 | pccompile = re.compile(r"aggr-\[po(\d+)\]") 38 | else: 39 | pccompile = re.compile(r"aggr-\[(po\d+)\]") 40 | if pccompile.search(x): 41 | return pccompile.group(1) 42 | else: 43 | return None 44 | def get_eth(self,x, num_only=False): 45 | if num_only: 46 | if re.search(r"phys-\[eth(.*)\]",x): 47 | return re.search(r"phys-\[eth(.*)\]",x).group(1) 48 | else: 49 | return None 50 | else: 51 | if re.search(r"phys-\[(eth.*)\]",x): 52 | return re.search(r"phys-\[(eth.*)\]",x).group(1) 53 | else: 54 | return None 55 | def parse_pod_leaf_phyinterface(self, x, returntype='dict'): 56 | if re.search(r"pod-(\d+)\/paths-(\d+)\/pathep-\[(.*)\]",x): 57 | self._physpath = re.findall(r"pod-(\d+)\/paths-(\d+)\/pathep-\[(.*)\]",x) 58 | import pdb; pdb.set_trace() 59 | self._pod, self._leaf, self._interface = self._physpath[0] 60 | if returntype == 'dict': 61 | return {'pod':self._pod,'leaf':self._leaf,'interface':self._interface} 62 | elif returntype == 'list': 63 | return self._physpath[0] 64 | else: 65 | raise NotImplementedError 66 | else: 67 | return None 68 | 69 | 70 | 71 | class epgbase(): 72 | def parse_tenant_app_epg(self,x, returntype='dict'): 73 | if re.search(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x): 74 | self._dngroups = re.findall(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x) 75 | self._tenant, self._app, self._epg = self._dngroups[0] 76 | if returntype == 'dict': 77 | return {'tenant':self._dngroups[0],'app':self._dngroups[1],'epg':self._dngroups[2]} 78 | elif returntype == 'list': 79 | return self._dngroups[0] 80 | else: 81 | raise NotImplementedError 82 | else: 83 | return None 84 | @staticmethod 85 | def _parse_tenant_app_epg(x, returntype='dict'): 86 | if re.search(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x): 87 | _dngroups = re.findall(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x) 88 | _tenant, _app, _epg = _dngroups[0] 89 | if returntype == 'dict': 90 | return {'tenant':_dngroups[0],'app':_dngroups[1],'epg':_dngroups[2]} 91 | elif returntype == 'list': 92 | return _dngroups[0] 93 | else: 94 | raise NotImplementedError 95 | else: 96 | return None 97 | 98 | def tenantappepg_formatter(self, x=None, delimiter='/'): 99 | if x == None: 100 | if hasattr(self,'tenant') and hasattr(self,'app') and hasattr(self,'epg'): 101 | return delimiter.join((self.tenant,self.app,self.epg)) 102 | else: 103 | return None 104 | elif isinstance(x,str) or isinstance(x,unicode): 105 | if re.search(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x): 106 | self.dngroups = re.findall(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x) 107 | return delimiter.join(*self.dngroups) 108 | else: 109 | return None 110 | elif isinstance(x,list) or isinstance(x,tuple): 111 | return delimiter.join(x) 112 | else: 113 | return None 114 | @staticmethod 115 | def _tenantappepg_formatter(x, delimiter='/'): 116 | if isinstance(x,str) or isinstance(x,unicode): 117 | if re.search(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x): 118 | dngroups = re.findall(r"tn-(.*)\/ap-(.*)\/epg-([^/]*)",x) 119 | return delimiter.join(*dngroups) 120 | else: 121 | return None 122 | elif isinstance(x,list) or isinstance(x,tuple): 123 | return delimiter.join(x) 124 | else: 125 | return None 126 | 127 | 128 | 129 | 130 | class interfacelower(interfacebase,epgbase): 131 | def __init__(self,kwargs): 132 | self.__dict__.update(**kwargs) 133 | 134 | 135 | if __name__ == '__main__': 136 | interfacelist = [{'dn': u'topology/pod-1/paths-101/pathep-[eth1/34]', 'leaf': u'leaf-101', 'name': u'eth1/34', 'descr': u'', 'number': None, 'fexethname': None, 'fullethname': u'eth1/34', 'removedint': u'topology/pod-1/paths-101', 'shortname': u'34', 'epgfvRsPathAttlist': [], 'fex': None}, 137 | {'dn': u'topology/pod-1/paths-102/pathep-[eth1/34]', 'leaf': u'leaf-101', 'name': u'eth1/34', 'descr': u'', 'number': None, 'fexethname': None, 'fullethname': u'eth1/34', 'removedint': u'topology/pod-1/paths-102', 'shortname': u'34', 'epgfvRsPathAttlist': [], 'fex': None}, 138 | {'dn': u'topology/pod-1/paths-101/pathep-[eth1/35]', 'leaf': u'leaf-101', 'name': u'eth1/35', 'descr': u'', 'number': None, 'fexethname': None, 'fullethname': u'eth1/35', 'removedint': u'topology/pod-1/paths-101', 'shortname': u'35', 'epgfvRsPathAttlist': [], 'fex': None}] 139 | 140 | newinterfacelist = [interobject(x) for x in interfacelist] 141 | finalinfralist = {k:list(g) for k, g in itertools.groupby(newinterfacelist, key=lambda x: x.fullethname)} 142 | #dn = "uni/tn-SI/ap-APP-AD/epg-EPG-VL11-AD/fltCnts" 143 | interfacedn = 'topology/pod-1/paths-101/pathep-[eth1/39]' 144 | #for x in newinterfacelist: 145 | j = interfacelower({'dn':interfacedn}) 146 | print(j.parse_pod_leaf_phyinterface(interfacedn, returntype='dict')) 147 | # print(j.tenantappepg_formatter()) 148 | 149 | 150 | import pdb; pdb.set_trace() -------------------------------------------------------------------------------- /localutils/program_globals.py: -------------------------------------------------------------------------------- 1 | TOKEN = "" 2 | USER = "" 3 | APIC = "" 4 | TIME = "" -------------------------------------------------------------------------------- /misc_unfinished_scripts/EPGstoInterfaces.txt: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | def displaycurrenttime(): 12 | currenttime = datetime.datetime.now() 13 | return str(currenttime)[:-7] 14 | 15 | 16 | def GetRequest(url, icookie): 17 | method = "GET" 18 | cookies = 'APIC-cookie=' + icookie 19 | request = urllib2.Request(url) 20 | request.add_header("cookie", cookies) 21 | request.add_header("Content-trig", "application/json") 22 | request.add_header('Accept', 'application/json') 23 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 24 | def GetResponseData(url): 25 | response = GetRequest(url, cookie) 26 | result = json.loads(response.read()) 27 | return result['imdata'], result["totalCount"] 28 | 29 | def get_Cookie(): 30 | global cookie 31 | with open('/.aci/.sessions/.token', 'r') as f: 32 | cookie = f.read() 33 | 34 | 35 | PC 36 | url: https://localhost/api/node/class/fabricPathEp.json?query-target-filter=and(not(wcard(fabricPathEp.dn,%22__ui_%22)),eq(fabricPathEp.lagT,"link")) -------------------------------------------------------------------------------- /misc_unfinished_scripts/aci_health/most_recent_admin_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib2.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-trig", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def displaycurrenttime(): 31 | currenttime = datetime.datetime.now() 32 | return str(currenttime)[:-3] 33 | 34 | def time_difference(admin_time): 35 | currenttime = datetime.datetime.now() 36 | ref_admin_time = datetime.datetime.strptime(admin_time, '%Y-%m-%d %H:%M:%S.%f') 37 | return str(currenttime - ref_admin_time)[:-7] 38 | 39 | 40 | def askrefresh(): 41 | while True: 42 | refresh = raw_input("Return to admin list? [y=default|n]: ") or 'y' 43 | if refresh[0].lower() == 'y': 44 | return True 45 | elif refresh[0].lower() == 'n': 46 | return False 47 | else: 48 | continue 49 | 50 | 51 | def gatheranddisplayrecentadmins(): 52 | while True: 53 | getCookie() 54 | os.system('clear') 55 | print("Current time = " + displaycurrenttime()) 56 | url = """https://localhost/api/node/class/aaaModLR.json?query-target-filter=not(wcard(aaaModLR.dn,%22__ui_%22))&order-by=aaaModLR.created|desc&page=0&page-size=50""" 57 | result, totauserount = GetResponseData(url) 58 | print('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','User','admin Summary')) 59 | print('-'*175) 60 | admindict = {} 61 | for num,admin in enumerate(result,1): 62 | if admin.get('aaaModLR'): 63 | admindescr = admin['aaaModLR']['attributes']['descr'].split() 64 | admindescr = ' '.join(admindescr) 65 | if len(admindescr) > 120: 66 | summaryadmindescr = admindescr[:120] + '...' 67 | else: 68 | summaryadmindescr = admindescr 69 | admincreated = ' '.join(admin['aaaModLR']['attributes']['created'].split('T')) 70 | admintrig = admin['aaaModLR']['attributes']['trig'] 71 | adminuser = admin['aaaModLR']['attributes']['user'] 72 | admindn = admin['aaaModLR']['attributes']['dn'] 73 | diff_time = time_difference(admincreated[:-6]) 74 | admindict[num] = [admincreated[:-6],admintrig,adminuser,admindn,admindescr] 75 | print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,admincreated[:-6],diff_time,admintrig,adminuser,summaryadmindescr)) 76 | 77 | while True: 78 | moredetails = raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 79 | if moredetails == '': 80 | break 81 | if moredetails.isdigit() and admindict.get(int(moredetails)): 82 | break 83 | else: 84 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 85 | if moredetails == '': 86 | continue 87 | diff_time = time_difference(admindict[int(moredetails)][0]) 88 | print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected')) 89 | print('-'*120) 90 | print('{:26}{:20}{:18}{:18}{}\n'.format(admindict[int(moredetails)][0],diff_time, admindict[int(moredetails)][1],admindict[int(moredetails)][2],'/'.join(str(admindict[int(moredetails)][3]).split('/')[:-1]))) 91 | print('admin Details') 92 | print('-'*15) 93 | print(admindict[int(moredetails)][4]) 94 | print('\n\n') 95 | 96 | refresh = askrefresh() 97 | if refresh == True: 98 | continue 99 | else: 100 | print('\nEnding Program...\n') 101 | break 102 | 103 | 104 | def main(): 105 | gatheranddisplayrecentadmins() 106 | 107 | 108 | if __name__ == '__main__': 109 | try: 110 | main() 111 | except KeyboardInterrupt as k: 112 | print("\n\nExiting Program....") 113 | exit() 114 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/aci_health/most_recent_event_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib2.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-trig", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def displaycurrenttime(): 31 | currenttime = datetime.datetime.now() 32 | return str(currenttime)[:-3] 33 | 34 | def time_difference(event_time): 35 | currenttime = datetime.datetime.now() 36 | ref_event_time = datetime.datetime.strptime(event_time, '%Y-%m-%d %H:%M:%S.%f') 37 | return str(currenttime - ref_event_time)[:-7] 38 | 39 | def askrefresh(): 40 | while True: 41 | refresh = raw_input("Return to event list? [y=default|n]: ") or 'y' 42 | if refresh[0].lower() == 'y': 43 | return True 44 | elif refresh[0].lower() == 'n': 45 | return False 46 | else: 47 | continue 48 | 49 | 50 | def gatheranddisplayrecentevents(): 51 | while True: 52 | getCookie() 53 | os.system('clear') 54 | print("Current time = " + displaycurrenttime()) 55 | print("\nEvents loading...\n") 56 | url = """https://localhost/api/node/class/eventRecord.json?query-target-filter=not(wcard(eventRecord.dn,%22__ui_%22))&order-by=eventRecord.created|desc&page=0&page-size=50""" 57 | result, totalcount = GetResponseData(url) 58 | os.system('clear') 59 | print("Current time = " + displaycurrenttime()) 60 | print('\n{:>5} {:26}{:20}{:24}{}'.format('#','Time','Time Difference', 'Port','Event Summary')) 61 | print('-'*175) 62 | eventdict = {} 63 | for num,event in enumerate(result,1): 64 | if event.get('eventRecord'): 65 | eventdescr = event['eventRecord']['attributes']['descr'].split() 66 | eventdescr = ' '.join(eventdescr) 67 | if len(eventdescr) > 120: 68 | summaryeventdescr = eventdescr[:120] + '...' 69 | else: 70 | summaryeventdescr = eventdescr 71 | eventcreated = ' '.join(event['eventRecord']['attributes']['created'].split('T')) 72 | eventtrig = event['eventRecord']['attributes']['trig'] 73 | eventuser = event['eventRecord']['attributes']['user'] 74 | eventdn = event['eventRecord']['attributes']['dn'] 75 | if 'eth' in eventdn and not 'extpaths' in eventdn: 76 | leaf = re.search(r'(node-[0-9]{1,3})|(paths-[0-9]{1,3})', eventdn).group() 77 | if leaf.startswith('paths'): 78 | leaf = leaf.replace('paths', 'leaf') 79 | elif leaf.startswith('node'): 80 | leaf = leaf.replace('node', 'leaf') 81 | interface = re.search(r'eth.*\/[0-9]{1,3}\]', eventdn).group() 82 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 83 | elif re.search(r'po[0-9]*\]', eventdn): 84 | leaf = re.search(r'node-[0-9]{1,3}', eventdn).group() 85 | leaf = leaf.replace('node', 'leaf') 86 | interface = re.search(r'po[0-9]*\]', eventdn).group() 87 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 88 | #elif 'rsoosPath' in eventdn and not 'extpaths' in eventdn: 89 | # leaf = re.search(r'protpaths-[0-9]{3}-[0-9]{3}', eventdn).group() 90 | # leaf = leaf.replace('protpaths', 'VPC node') 91 | # interface = re.search(r'pathep-.*\]', eventdn).group() 92 | # interface = interface.replace('pathep-', "") 93 | # portinterfaces = '{} {}'.format(leaf,interface[:-1]) 94 | #elif 'rsoosPath' in eventdn and 'extpaths' in eventdn: 95 | # leaf = re.search(r'paths-[0-9]{3}', eventdn).group() 96 | # leaf = leaf.replace('paths','node') 97 | # fex = re.search(r'extpaths-.*\]', eventdn).group() 98 | # interface = re.search(r'eth[0-9]{1,3}/[0-9]{1,3}', eventdn).group() 99 | # portinterfaces = '{} {} {}'.format(leaf,fex,interface) 100 | else: 101 | portinterfaces = "" 102 | diff_time = time_difference(eventcreated[:-6]) 103 | eventdict[num] = [eventcreated[:-6],eventtrig,eventuser,eventdn,eventdescr] 104 | print('{:5}.) {:26}{:20}{:24}{}'.format(num,eventcreated[:-6],diff_time,portinterfaces,summaryeventdescr)) 105 | 106 | while True: 107 | moredetails = raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 108 | if moredetails == '': 109 | break 110 | if moredetails.isdigit() and eventdict.get(int(moredetails)): 111 | break 112 | else: 113 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 114 | if moredetails == '': 115 | continue 116 | diff_time = time_difference(eventdict[int(moredetails)][0]) 117 | print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected')) 118 | print('-'*120) 119 | print('{:26}{:20}{:18}{:18}{}\n'.format(eventdict[int(moredetails)][0],diff_time, eventdict[int(moredetails)][1],eventdict[int(moredetails)][2],'/'.join(str(eventdict[int(moredetails)][3]).split('/')[:-1]))) 120 | print('Event Details') 121 | print('-'*15) 122 | print(eventdict[int(moredetails)][4]) 123 | print('\n\n') 124 | refresh = askrefresh() 125 | if refresh == True: 126 | continue 127 | else: 128 | print('\nEnding Program...\n') 129 | break 130 | 131 | 132 | def main(): 133 | gatheranddisplayrecentevents() 134 | 135 | 136 | if __name__ == '__main__': 137 | try: 138 | main() 139 | except KeyboardInterrupt as k: 140 | print("\n\nExiting Program....") 141 | exit() 142 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/aci_health/most_recent_fault_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib2.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-Type", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def displaycurrenttime(): 31 | currenttime = datetime.datetime.now() 32 | return str(currenttime)[:-3] 33 | 34 | def time_difference(fault_time): 35 | currenttime = datetime.datetime.now() 36 | ref_fault_time = datetime.datetime.strptime(fault_time, '%Y-%m-%d %H:%M:%S.%f') 37 | return str(currenttime - ref_fault_time)[:-7] 38 | 39 | 40 | def askrefresh(): 41 | while True: 42 | refresh = raw_input("Return to fault list? [y=default|n]: ") or 'y' 43 | if refresh[0].lower() == 'y': 44 | return True 45 | elif refresh[0].lower() == 'n': 46 | return False 47 | else: 48 | continue 49 | 50 | 51 | def gatheranddisplayrecentfaults(): 52 | while True: 53 | getCookie() 54 | os.system('clear') 55 | print("Current time = " + displaycurrenttime()) 56 | url = """https://localhost/api/node/class/faultInfo.json?query-target-filter=and(ne(faultInfo.severity,"cleared"))&order-by=faultInfo.lastTransition|desc&page=0&page-size=100""" 57 | result, totalcount = GetResponseData(url) 58 | print('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','Fault-State','Fault Summary')) 59 | print('-'*175) 60 | faultdict = {} 61 | for num,fault in enumerate(result,1): 62 | if fault.get('faultInst'): 63 | faultdescr = fault['faultInst']['attributes']['descr'].split() 64 | faultdescr = ' '.join(faultdescr) 65 | if len(faultdescr) > 120: 66 | summaryfaultdescr = faultdescr[:120] + '...' 67 | else: 68 | summaryfaultdescr = faultdescr 69 | faultlastTransition = ' '.join(fault['faultInst']['attributes']['lastTransition'].split('T')) 70 | faulttype = fault['faultInst']['attributes']['type'] 71 | faultstate = fault['faultInst']['attributes']['lc'] 72 | faultdn = fault['faultInst']['attributes']['dn'] 73 | diff_time = time_difference(faultlastTransition[:-6]) 74 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 75 | print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 76 | else: 77 | faultdescr = fault['faultDelegate']['attributes']['descr'].split() 78 | faultdescr = ' '.join(faultdescr) 79 | if len(faultdescr) > 120: 80 | summaryfaultdescr = faultdescr[:120] + '...' 81 | else: 82 | summaryfaultdescr = faultdescr 83 | faultlastTransition = ' '.join(fault['faultDelegate']['attributes']['lastTransition'].split('T')) 84 | faulttype = fault['faultDelegate']['attributes']['type'] 85 | faultstate = fault['faultDelegate']['attributes']['lc'] 86 | faultdn = fault['faultDelegate']['attributes']['dn'] 87 | diff_time = time_difference(faultlastTransition[:-6]) 88 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 89 | print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 90 | while True: 91 | moredetails = raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 92 | if moredetails == '': 93 | break 94 | if moredetails.isdigit() and faultdict.get(int(moredetails)): 95 | break 96 | else: 97 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 98 | if moredetails == '': 99 | continue 100 | diff_time = time_difference(faultdict[int(moredetails)][0]) 101 | print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','Fault-State','Object-Affected')) 102 | print('-'*120) 103 | print('{:26}{:20}{:18}{:18}{}\n'.format(faultdict[int(moredetails)][0],diff_time, faultdict[int(moredetails)][1],faultdict[int(moredetails)][2],'/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1]))) 104 | print('Fault Details') 105 | print('-'*15) 106 | print(faultdict[int(moredetails)][4]) 107 | print('\n\n') 108 | refresh = askrefresh() 109 | if refresh == True: 110 | continue 111 | else: 112 | print('\nEnding Program...\n') 113 | break 114 | 115 | 116 | def main(): 117 | gatheranddisplayrecentfaults() 118 | 119 | 120 | if __name__ == '__main__': 121 | try: 122 | main() 123 | except KeyboardInterrupt as k: 124 | print("\n\nExiting Program....") 125 | exit() 126 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/endpoint_history2.0.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | 10 | 11 | def GetRequest(url, icookie): 12 | method = "GET" 13 | cookies = 'APIC-cookie=' + icookie 14 | request = urllib2.Request(url) 15 | request.add_header("cookie", cookies) 16 | request.add_header("Content-Type", "application/json") 17 | request.add_header('Accept', 'application/json') 18 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 19 | 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def validateipaddress(ip): 26 | result = re.search(r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$', ip) 27 | if result: 28 | return True 29 | return False 30 | 31 | def findipaddress(): 32 | ipaddr = raw_input("\nWhat is the ip address?: ") 33 | # verify a valid ip format and its not a blank input 34 | if not validateipaddress(ipaddr) or ipaddr == '': 35 | return 36 | url = """https://localhost/api/node/class/fvCEp.json?rsp-subtree=full&rsp-subtree-include=required&rsp-subtree-filter=eq(fvIp.addr,"{}")""".format(ipaddr) 37 | result, totalcount = GetResponseData(url) 38 | try: 39 | # Check to see if there is no 'live' history of ip address 40 | if totalcount == '0': 41 | print('\n') 42 | print("{:26}\t{:15}\t{:18}\t{}".format("Date", "encap-vlan", "Ip Address", "Mac Address")) 43 | print('-'*97) 44 | # \x1b[41;1m is a special sequece to start red color for ansii color in terminal and \x1b[0m returns colors to normal 45 | print('\x1b[41;1mNo "LIVE Endpoint" IP found...check event history\x1b[0m\n') 46 | print('\n') 47 | # If 'live' history found, print history 48 | else: 49 | mac = result[0]['fvCEp']['attributes']['mac'] 50 | #encap = result[0]['fvCEp']['attributes']['encap'] 51 | dn = result[0]['fvCEp']['attributes']['dn'] 52 | # split 'dn' into a list and only keep uni->epg 53 | dnpath = '/'.join(dn.split('/')[:4]) 54 | print('\n') 55 | print("{:26}\t{:15}\t{:18}\t{:20}\t{}".format("Date", "encap-vlan", "Ip Address", "Mac Address", "Path")) 56 | print('-'*115) 57 | #url2 = """https://localhost/api/node/mo/uni/tn-SI/ap-APP-ISE/epg-EPG-VL10-ISE/cep-{}.json?query-target=subtree&target-subtree-class=fvCEp,fvRsCEpToPathEp,fvRsHyper,fvRsToNic,fvRsToVm""".format(mac) 58 | url3 = """https://localhost/mqapi2/troubleshoot.eptracker.json?ep={}/cep-{}&order-by=troubleshootEpTransition.date|desc&page=0&page-size=25""".format(dnpath,mac) 59 | 60 | result3, totalcount3 = GetResponseData(url3) 61 | for entry in result3: 62 | mac = entry['troubleshootEpTransition']['attributes']['mac'] 63 | ip = entry['troubleshootEpTransition']['attributes']['ip'] 64 | date = entry['troubleshootEpTransition']['attributes']['date'][:-6] 65 | encap_vlan = entry['troubleshootEpTransition']['attributes']['encap'] 66 | path = entry['troubleshootEpTransition']['attributes']['path'] 67 | 68 | leaf = re.search(r'paths-[0-9]{3}',path) 69 | if leaf: 70 | leaf = leaf.group().replace('paths-', '') 71 | interface = re.search(r'\[.*\]',path) 72 | if interface: 73 | interface = interface.group()[1:-1] 74 | fex = re.search(r'extpaths-[0-9]{3}',path) 75 | if fex: 76 | fex = fex.group().replace('extpaths-', '') 77 | path = 'leaf{} fex={} {}'.format(leaf,fex,interface) 78 | else: 79 | path = 'leaf{} {}'.format(leaf,interface) 80 | 81 | print("{:26}\t{:15}\t{:18}\t{:20}\t{}".format(date, encap_vlan, ip, mac, path) ) 82 | except Exception as e: 83 | print(e) 84 | return 85 | history = raw_input("\nWould you like to see event history of {}? [y/n]: ".format(ipaddr)) 86 | if history != '' and history.lower() == 'y': 87 | return ipaddr 88 | else: 89 | return 0 90 | 91 | def searcheventrecords(ipaddr): 92 | #event record code E4209236 is "ip detached event" 93 | url = """https://localhost/api/node/class/eventRecord.json?query-target-filter=and(eq(eventRecord.code,"E4209236"))&""" \ 94 | """query-target-filter=and(wcard(eventRecord.descr,"{ipaddr}$"))&order-by=eventRecord.created|desc&page=0&page-size=25""".format(ipaddr=ipaddr) 95 | result, totalcount = GetResponseData(url) 96 | print('\n') 97 | if totalcount == '0': 98 | print("{:.<45}0\n".format("Searching Event Records")) 99 | else: 100 | print("{:.<45}Found {} Events\n".format("Searching Event Records",totalcount)) 101 | 102 | print("{:26}{:12}".format('Date','Description', )) 103 | print('-'*90) 104 | if totalcount == '0': 105 | print("\x1b[41;1mNo event history found for IP {}\x1b[0m\n\n".format(ipaddr)) 106 | return 107 | for event in result: 108 | timestamp = event['eventRecord']['attributes']['created'] 109 | descr = event['eventRecord']['attributes']['descr'] 110 | dn = event['eventRecord']['attributes']['dn'] 111 | mac = re.search(r'cep-.{17}', dn) 112 | print("{:26}{:^12} [{}]".format(timestamp[:-6],descr,'mac: ' + mac.group()[4:])) 113 | 114 | 115 | def main(): 116 | while True: 117 | os.system('clear') 118 | ipaddr = findipaddress() 119 | # If user desides not to search events but wants to look up another ip address 120 | if ipaddr == 0: 121 | ask = raw_input("\nCheck another ip address? [y/n]: ") 122 | # if 'y' then restart the while loop to findipaddress() 123 | if ask.lower() == 'y' and ask != '': 124 | continue 125 | else: 126 | exit() 127 | # If user did want to search events and then look up another ip address afterwards 128 | elif ipaddr: 129 | searcheventrecords(ipaddr) 130 | ask = raw_input("\nCheck another ip address? [y/n]: ") 131 | # if 'y' then restart the while loop to findipaddress() 132 | if ask.lower() == 'y' and ask != '': 133 | continue 134 | else: 135 | exit() 136 | 137 | if __name__ == '__main__': 138 | 139 | with open('/.aci/.sessions/.token', 'r') as f: 140 | cookie = f.read() 141 | 142 | main() 143 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/enpoint_gather_compare.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | import ipaddress 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib2.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-trig", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def get_Cookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | class fvCEP(): 31 | def __init__(self, mac=None, ifId=None, name=None, 32 | pcTag=None, dn=None, flags=None): 33 | self.mac = mac 34 | self.ifId = ifId 35 | self.name = name 36 | self.pcTag = pcTag 37 | self.dn = dn 38 | self.flags = flags 39 | def __repr__(self): 40 | return self.dn 41 | def __getitem__(self, mac): 42 | if mac in self.mac: 43 | return self.mac 44 | else: 45 | return None 46 | 47 | class endpointip(): 48 | def __init__(self, forceResolve=None, ifId=None, name=None, 49 | pcTag=None, dn=None, flags=None): 50 | self.addr = addr 51 | self.ifId = ifId 52 | self.name = name 53 | self.pcTag = pcTag 54 | self.dn = dn 55 | self.flags = flags 56 | def __repr__(self): 57 | return self.dn 58 | def __getitem__(self, addr): 59 | if addr in self.addr: 60 | return self.addr 61 | else: 62 | return None 63 | 64 | get_Cookie() 65 | url = """https://localhost/api/class/epmMacEp.json""" 66 | result, totalamount = GetResponseData(url) 67 | epmMacEPlist = [x['epmMacEp']['attributes']['addr'] for x in result] 68 | print(len(epmMacEPlist)) 69 | set1 = set(epmMacEPlist) 70 | print(len(set1)) 71 | 72 | 73 | print('\n\n') 74 | url = """https://localhost/api/class/fvCEp.json""" 75 | result, totalamount = GetResponseData(url) 76 | fvCEplist = [x['fvCEp']['attributes']['mac'] for x in result] 77 | print(len(fvCEplist)) 78 | set2 = set(fvCEplist) 79 | print(len(set2)) 80 | 81 | print(set2-set1) 82 | 83 | 84 | #https://192.168.255.2/api/class/epmMacEp.json?rsp-subtree=full 85 | # leaf directly https://192.168.255.101/api/class/epmMacEp.json?rsp-subtree=full -------------------------------------------------------------------------------- /misc_unfinished_scripts/futureprojects.txt: -------------------------------------------------------------------------------- 1 | show interface trunk 2 | Automatic span session for endpoint to designated wireshark server 3 | automate phyical port setups (vpc) and access ports 4 | vpc1 vpc2 5 | ___ ____ 6 | cdp on 7 | lldp on 8 | lacp on 9 | 10 | access1 11 | ____ 12 | static routes 13 | enpoints on interface 14 | interface desciptions 15 | Show Leaf/Spine/APIC info 16 | EPG to EPG troubleshooting 17 | 18 | 19 | compEpPD contains loadbalance based on port-group vmware -------------------------------------------------------------------------------- /misc_unfinished_scripts/geolocationswitches.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib2.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-Type", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def main(): 31 | url = 'https://localhost/api/node/class/geoRsNodeLocation.json' 32 | result, totalCount = GetResponseData(url) 33 | print(result) 34 | 35 | if __name__ == '__main__': 36 | main() -------------------------------------------------------------------------------- /misc_unfinished_scripts/gether_allendpoints_to_interface.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import ipaddress 9 | 10 | 11 | def GetRequest(url, icookie): 12 | method = "GET" 13 | cookies = 'APIC-cookie=' + icookie 14 | request = urllib2.Request(url) 15 | request.add_header("cookie", cookies) 16 | request.add_header("Content-Type", "application/json") 17 | request.add_header('Accept', 'application/json') 18 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 19 | def GetResponseData(url): 20 | response = GetRequest(url, cookie) 21 | result = json.loads(response.read()) 22 | return result['imdata'], result["totalCount"] 23 | 24 | class fvCEp(): 25 | def __init__(self, mac=None, name=None, encap=None, 26 | lcC=None, dn=None, fvRsVm=None, fvRsHyper=None, 27 | fvRsCEpToPathEp=None, ip=None, fvIplist=[]): 28 | self.mac = mac 29 | self.name = name 30 | self.encap = encap 31 | self.dn = dn 32 | self.lcC = lcC 33 | self.fvRsVm = fvRsVm 34 | self.fvRsHyper = fvRsHyper 35 | self.ip = ip 36 | #self.iplist = iplist 37 | self.fvIplist = fvIplist 38 | self.fvRsCEpToPathEp = fvRsCEpToPathEp 39 | def __repr__(self): 40 | return self.dn 41 | def __getitem__(self, mac): 42 | if mac in self.mac: 43 | return self.mac 44 | else: 45 | return None 46 | def showips(self): 47 | iplist = [fvIP.addr for fvIP in self.fvIplist] 48 | return ', '.join(iplist) 49 | 50 | 51 | class fvIp(): 52 | def __init__(self, addr=None, rn=None,fvReportingNodes=None): 53 | self.addr = addr 54 | self.rn = rn 55 | self.fvReportingNodes = fvReportingNodes 56 | def __repr__(self): 57 | return self.addr 58 | def __getitem__(self, addr): 59 | if addr in self.addr: 60 | return self.addr 61 | else: 62 | return None 63 | 64 | class fvRsCEpToPathEp(): 65 | def __init__(self, tDn=None, lcC=None, fvReportingNodes=[], forceResolve=None): 66 | self.lcC = lcC #shows location it learned if 'vmm' vmm knows it cause vmware, 'vmm,learned' means vmware and switch knows, if just 'learned' not vmm source 67 | self.tDn = tDn # location of learned interface "topology/pod-1/paths-102/extpaths-112/pathep-[eth1/25]" example 68 | self.fvReportingNodes = fvReportingNodes # looks like port-channels use fvReportingNode api class (describes leafs where ep is discovered) 69 | self.forceResolve = forceResolve 70 | def __repr__(self): 71 | return self.tDn 72 | 73 | class fvRsVm(): 74 | def __init__(self, state=None, tDn=None, dn=None): 75 | self.state = state 76 | self.dn = dn 77 | self.tDn = tDn #internal vm name to lookup vmware vm name 78 | def __repr__(self): 79 | return self.tDn 80 | 81 | class fvRsHyper(): 82 | def __init__(self, state=None, tDn=None): 83 | self.state = state 84 | self.tDn = tDn #hyperviser internal name to look up vmware host name 85 | def __repr__(self): 86 | return self.tDn 87 | 88 | def get_Cookie(): 89 | global cookie 90 | with open('/.aci/.sessions/.token', 'r') as f: 91 | cookie = f.read() 92 | 93 | 94 | def gather_fvCEp_fullinfo(result): 95 | eplist = [] 96 | fvRsVmobject = None 97 | fvRsCEpToPathEpobject = None 98 | fvRsHyperobject = None 99 | fvIplist = [] 100 | for ep in result: 101 | fvReportingNodes = [] 102 | mac = ep['fvCEp']['attributes']['mac'] 103 | name = ep['fvCEp']['attributes']['name'] 104 | encap = ep['fvCEp']['attributes']['encap'] 105 | lcC = ep['fvCEp']['attributes']['lcC'] 106 | dn = ep['fvCEp']['attributes']['dn'] 107 | ip = ep['fvCEp']['attributes']['ip'] 108 | if ep['fvCEp'].get('children'): 109 | for ceptopath in ep['fvCEp']['children']: 110 | if ceptopath.get('fvRsCEpToPathEp') and ceptopath['fvRsCEpToPathEp']['attributes']['state'] == 'formed': 111 | fvRsCEpToPathEp_tDn = ceptopath['fvRsCEpToPathEp']['attributes']['tDn'] 112 | fvRsCEpToPathEp_lcC = ceptopath['fvRsCEpToPathEp']['attributes']['lcC'] 113 | fvRsCEpToPathEp_forceResolve = ceptopath['fvRsCEpToPathEp']['attributes']['forceResolve'] 114 | fvRsCEpToPathEpobject = fvRsCEpToPathEp(forceResolve=fvRsCEpToPathEp_forceResolve, 115 | tDn=fvRsCEpToPathEp_tDn, lcC=fvRsCEpToPathEp_lcC) 116 | elif ceptopath.get('fvIp'): 117 | fvIp_addr = ceptopath['fvIp']['attributes']['addr'] 118 | fvIp_rn = ceptopath['fvIp']['attributes']['rn'] 119 | if ceptopath['fvIp'].get('children'): 120 | fvReportingNodes = [node['fvReportingNode']['attributes']['rn'] for node in ceptopath['fvIp']['children']] 121 | else: 122 | fvReportingNodes = None 123 | fvIplist.append(fvIp(addr=fvIp_addr, rn=fvIp_rn, 124 | fvReportingNodes=fvReportingNodes)) 125 | elif ceptopath.get('fvRsVm') and ceptopath['fvRsVm']['attributes']['state'] == 'formed': 126 | fvRsVm_state = ceptopath['fvRsVm']['attributes']['state'] 127 | fvRsVm_tDn = ceptopath['fvRsVm']['attributes']['tDn'] 128 | fvRsVmobject = fvRsVm(state=fvRsVm_state, 129 | tDn=fvRsVm_tDn) 130 | elif ceptopath.get('fvRsHyper') and ceptopath['fvRsHyper']['attributes']['state'] == 'formed': 131 | fvRsHyper_state = ceptopath['fvRsHyper']['attributes']['state'] 132 | fvRsHyper_tDn = ceptopath['fvRsHyper']['attributes']['tDn'] 133 | fvRsHyperobject = fvRsHyper(state=fvRsHyper_state, 134 | tDn=fvRsHyper_tDn) 135 | eplist.append(fvCEp(mac=mac, name=name, encap=encap, 136 | lcC=lcC, dn=dn, fvRsVm=fvRsVmobject, fvRsCEpToPathEp=fvRsCEpToPathEpobject, 137 | ip=ip, fvRsHyper=fvRsHyperobject, fvIplist=fvIplist)) 138 | fvIplist = [] 139 | return eplist 140 | 141 | 142 | def mac_path_function(): 143 | url = """https://localhost/api/node/class/fvCEp.json?rsp-subtree=full&target-subtree-class=fvCEp,fvRsCEpToPathEp""" 144 | result, totalcount = GetResponseData(url) 145 | fvCEplist = gather_fvCEp_fullinfo(result) 146 | #print(fvCEplist) 147 | for x in fvCEplist: 148 | #print("{:25}{:20}{:20}{}".format(x.mac, x.ip, x.fvIplist, x.fvRsCEpToPathEp)) 149 | print("{},{},{},{}".format(x.mac,x.ip,x.fvIplist,x.fvRsCEpToPathEp)) 150 | print(totalcount) 151 | #for fvCEp in fvCEplist: 152 | # result, totalcount = GetResponseData(url) 153 | # completefvCEplist = gather_fvCEp_fullinfo(result) 154 | # #print(completefvCEplist) 155 | # #Display current endpoint info 156 | # 157 | # find_current_ep_info(completefvCEplist[0], totalcount) 158 | # #Display current known endpoint history 159 | # display_live_history_info(completefvCEplist[0], totalcount) 160 | 161 | 162 | def main(): 163 | get_Cookie() 164 | mac_path_function() 165 | 166 | if __name__ == '__main__': 167 | main() 168 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/health_reasons.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import ipaddress 9 | 10 | 11 | ipaddr = None 12 | 13 | def GetRequest(url, icookie): 14 | method = "GET" 15 | cookies = 'APIC-cookie=' + icookie 16 | request = urllib2.Request(url) 17 | request.add_header("cookie", cookies) 18 | request.add_header("Content-Type", "application/json") 19 | request.add_header('Accept', 'application/json') 20 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 21 | def GetResponseData(url): 22 | response = GetRequest(url, cookie) 23 | result = json.loads(response.read()) 24 | return result['imdata'], result["totalCount"] 25 | 26 | def get_Cookie(): 27 | global cookie 28 | with open('/.aci/.sessions/.token', 'r') as f: 29 | cookie = f.read() 30 | get_Cookie() 31 | #url = """https://localhost/api/node/mo/topology/pod-1/node-101/sys.json?query-target=children&rsp-subtree-include=health,fault-count""" 32 | #result, totalcount = GetResponseData(url) 33 | #for object in result: 34 | # for currentobject in object: 35 | # print(currentobject) 36 | # if object[currentobject]['children']: 37 | # for ob in object[currentobject]['children']: 38 | # if ob.get('healthInst'): 39 | # print(ob['healthInst']) 40 | 41 | 42 | #url = """https://localhost/api/node/mo/topology/pod-1/node-102/sys/ch.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""" 43 | #result, totalcount = GetResponseData(url) 44 | #for object in result: 45 | # for currentobject in object: 46 | # print(currentobject, object[currentobject]['children'][0]['healthInst']['attributes']['cur']) 47 | 48 | url = """https://localhost/api/node/mo/topology/pod-1/node-102/sys.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""" 49 | result, totalcount = GetResponseData(url) 50 | for object in result: 51 | for currentobject in object: 52 | #print(currentobject, object[currentobject]['children'][0]['healthInst']['attributes']['cur'], object[currentobject]['attributes']['dn']) 53 | url = """https://localhost/api/node/mo/{}.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""".format(object[currentobject]['attributes']['dn']) 54 | #print(url) 55 | result2, totalcount = GetResponseData(url) 56 | for object2 in result2: 57 | for currentobject2 in object2: 58 | #pass 59 | #print(currentobject2, object2[currentobject2]['children'][0]['healthInst']['attributes']['cur'], object2[currentobject2]['attributes']['dn']) 60 | url = """https://localhost/api/node/mo/{}.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""".format(object2[currentobject2]['attributes']['dn']) 61 | result3, totalcount = GetResponseData(url) 62 | for object3 in result3: 63 | for currentobject3 in object3: 64 | print(currentobject3, object3[currentobject3]['children'][0]['healthInst']['attributes']['cur'], object3[currentobject3]['attributes']['dn']) 65 | #url = """https://localhost/api/node/class/faultInst.json?query-target-filter=eq(wcard(faultInst,"102"))""" 66 | #result, totalcount = GetResponseData(url) 67 | #print(result) -------------------------------------------------------------------------------- /misc_unfinished_scripts/healthistory.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | import itertools 11 | import trace 12 | import pdb 13 | import datetime 14 | 15 | def GetRequest(url, icookie): 16 | method = "GET" 17 | cookies = 'APIC-cookie=' + icookie 18 | request = urllib2.Request(url) 19 | request.add_header("cookie", cookies) 20 | request.add_header("Content-type", "application/json") 21 | request.add_header('Accept', 'application/json') 22 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 23 | def GetResponseData(url): 24 | response = GetRequest(url, cookie) 25 | result = json.loads(response.read()) 26 | return result['imdata'], result["totalCount"] 27 | 28 | 29 | 30 | class healthscores(): 31 | def __init__(self, **kwargs): 32 | self.__dict__.update(kwargs) 33 | def __repr__(self): 34 | return self.healthMin 35 | 36 | 37 | def grouper(iterable, n, fillvalue=''): 38 | "Collect data into fixed-length chunks or blocks" 39 | # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" 40 | args = [iter(iterable)] * n # creates list * n so args is a list of iters for iterable 41 | return itertools.izip_longest(*args, fillvalue=fillvalue) 42 | 43 | def get_Cookie(): 44 | global cookie 45 | with open('/.aci/.sessions/.token', 'r') as f: 46 | cookie = f.read() 47 | get_Cookie() 48 | url = """https://localhost/api/node/mo/topology.json?rsp-subtree-include=stats&rsp-subtree-class=fabricOverallHealthHist5min""" 49 | result, totalcount = GetResponseData(url) 50 | 51 | healthlist = [] 52 | for health in result[0]['fabricTopology']['children']: 53 | #print(health) 54 | healthlist.append(healthscores(**health['fabricOverallHealthHist5min']['attributes'])) 55 | healthlist = sorted(healthlist, key=lambda x: x.repIntvEnd) 56 | grouped = grouper(healthlist, 96) 57 | 58 | print(grouped) 59 | healthlist = zip(*grouped) 60 | for h in healthlist: 61 | print(h) 62 | #if h.healthMin < h.healthAvg: 63 | # aa = 31 64 | #else: 65 | # aa = 37 66 | #if h.healthMax > h.healthAvg: 67 | # cc = 32 68 | #else: 69 | # cc = 37 70 | #print('\x1b[1;{};40m{}\x1b[0m {} \x1b[1;{};40m{}\x1b[0m {}'.format(aa,h.healthMin,h.healthAvg,cc,h.healthMax, h.repIntvEnd)) 71 | #zip(h.healthMin, h.healthMax, h.healthAvg) 72 | 73 | 74 | #for a,b,c in kk: 75 | # if a < b: 76 | # aa = 31 77 | # else: 78 | # aa = 37 79 | # if c > b: 80 | # cc = 32 81 | # else: 82 | # cc = 37 83 | # print('\x1b[1;{};40m{}\x1b[0m {} \x1b[1;{};40m{}\x1b[0m'.format(aa,a,b,cc,c)) -------------------------------------------------------------------------------- /misc_unfinished_scripts/interface_information/interface-egps.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | #import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import os 9 | 10 | def GetRequest(url, icookie): 11 | method = "GET" 12 | cookies = 'APIC-cookie=' + icookie 13 | request = urllib2.Request(url) 14 | request.add_header("cookie", cookies) 15 | request.add_header("Content-Type", "application/json") 16 | request.add_header('Accept', 'application/json') 17 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 18 | def GetResponseData(url): 19 | response = GetRequest(url, cookie) 20 | result = json.loads(response.read()) 21 | return result['imdata'], result["totalCount"] 22 | 23 | def retrieve_leaf_list(): 24 | # Display available leafs beginning of script 25 | url = """https://localhost/api/node/mo/topology/pod-1.json?query-target=children&target-subtree-class=fabricNode&query-target-filter=and(wcard(fabricNode.id,"^1[0-9][0-9]"))""" 26 | result, totalcount = GetResponseData(url) 27 | #print(result) 28 | leafs = [leaf['fabricNode']['attributes']['id'] for leaf in result] 29 | #print('Available leafs to bounce ports...') 30 | return leafs 31 | 32 | def displayepgs(result): 33 | print('\n{:10}{:15}{}'.format('Tenant','APP','EPG')) 34 | print('-'*40) 35 | #print(result) 36 | if result[0]['l1PhysIf']['attributes']['layer'] == 'Layer3': 37 | print('Layer 3 interface, no EPGs\n') 38 | return 39 | if result[0]['l1PhysIf'].get('children'): 40 | for int in result[0]['l1PhysIf']['children']: 41 | for epgs in int['pconsCtrlrDeployCtx']['children']: 42 | epgpath = epgs['pconsResourceCtx']['attributes']['ctxDn'].split('/') 43 | #print(epgpath) 44 | tenant = epgpath[1][3:] 45 | app = epgpath[2][3:] 46 | epg = epgpath[3][4:] 47 | print('{:10}{:15}{}'.format(tenant,app,epg)) 48 | print('\n') 49 | else: 50 | print('No Epgs found...\n') 51 | 52 | 53 | with open('/.aci/.sessions/.token', 'r') as f: 54 | cookie = f.read() 55 | 56 | def gatherandstoreinterfacesforleaf(leaf): 57 | url = """https://localhost/api/node/class/topology/pod-1/node-101/l1PhysIf.json""" 58 | result, totalcount = GetResponseData(url) 59 | listofinterfaces = [interface['l1PhysIf']['attributes']['id'] for interface in result] 60 | return listofinterfaces 61 | 62 | def main(): 63 | fex = False 64 | print("\n1.) Physical interface\n" + 65 | "2.) Port-channel/vPC\n") 66 | int_type = raw_input("What is the interface type?: ") 67 | if int_type == '1': 68 | listleafs = retrieve_leaf_list() 69 | print('\nAvailable Leafs\n' + '-'*12) 70 | for leaf in sorted(listleafs): 71 | print(leaf)#Leaf' + ' Leaf'.join(leafs)) 72 | print('\r') 73 | while True: 74 | leaf = raw_input("What is leaf number?: ") 75 | if leaf in listleafs: 76 | break 77 | else: 78 | print('\x1b[41;1mInvalid or leaf does not exist...try again\x1b[0m\n') 79 | availableinterfaces = gatherandstoreinterfacesforleaf(leaf) 80 | #while True: 81 | # askfex = raw_input("Fex interface? [y|n] (default=n): ") or 'n' 82 | # if askfex[0].lower() == 'y': 83 | # fex = True 84 | # break 85 | # else: 86 | # break 87 | while True: 88 | if fex == True: 89 | interface = raw_input("What is the interface? (format: ethxxx/x/x): ") 90 | else: 91 | interface = raw_input("What is the interface? (format: ethx/x): ") 92 | if interface in availableinterfaces: 93 | break 94 | else: 95 | print('\x1b[41;1mInvalid or interface does not exist...try again\x1b[0m\n') 96 | 97 | url = """https://localhost/api/node/mo/topology/pod-1/node-{leaf}/sys/phys-[{interface}].json?rsp-subtree-include=full-deployment&target-node=all&target-path=l1EthIfToEPg""".format(leaf=leaf,interface=interface) 98 | #print(url) 99 | result, totalcount = GetResponseData(url) 100 | displayepgs(result) 101 | elif int_type == 2: 102 | pass 103 | else: 104 | pass 105 | 106 | 107 | 108 | if __name__ == '__main__': 109 | while True: 110 | main() 111 | ask = raw_input('Another interface? [y|n]: ') or 'n' 112 | #print(ask) 113 | if ask[0].lower() == 'y': 114 | continue 115 | else: 116 | break 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/most_recent_event_changes_no_vmware.py: -------------------------------------------------------------------------------- 1 | import re 2 | import readline 3 | import urllib2 4 | import json 5 | import ssl 6 | import os 7 | import datetime 8 | 9 | def displaycurrenttime(): 10 | currenttime = datetime.datetime.now() 11 | return str(currenttime)[:-3] 12 | 13 | def time_difference(event_time): 14 | currenttime = datetime.datetime.now() 15 | ref_event_time = datetime.datetime.strptime(event_time, '%Y-%m-%d %H:%M:%S.%f') 16 | return str(currenttime - ref_event_time)[:-7] 17 | 18 | 19 | def GetRequest(url, icookie): 20 | method = "GET" 21 | cookies = 'APIC-cookie=' + icookie 22 | request = urllib2.Request(url) 23 | request.add_header("cookie", cookies) 24 | request.add_header("Content-trig", "application/json") 25 | request.add_header('Accept', 'application/json') 26 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 27 | def GetResponseData(url): 28 | response = GetRequest(url, cookie) 29 | result = json.loads(response.read()) 30 | return result['imdata'], result["totalCount"] 31 | 32 | def getCookie(): 33 | global cookie 34 | with open('/.aci/.sessions/.token', 'r') as f: 35 | cookie = f.read() 36 | 37 | 38 | def askrefresh(): 39 | while True: 40 | refresh = raw_input("Return to event list? [y=default|n]: ") or 'y' 41 | if refresh[0].lower() == 'y': 42 | return True 43 | elif refresh[0].lower() == 'n': 44 | return False 45 | else: 46 | continue 47 | 48 | 49 | def gatheranddisplayrecentevents(): 50 | while True: 51 | getCookie() 52 | os.system('clear') 53 | print("Current time = " + displaycurrenttime()) 54 | print("\nEvents loading...\n") 55 | url = """https://localhost/api/node/class/eventRecord.json?query-target-filter=and(not(wcard(eventRecord.dn,%22__ui_%22)),ne(eventRecord.code,"E4204947"))&order-by=eventRecord.created|desc&page=0&page-size=100""" 56 | result, totalcount = GetResponseData(url) 57 | #print(result) 58 | os.system('clear') 59 | print("Current time = " + displaycurrenttime()) 60 | 61 | print('\n{:>5} {:26}{:20}{:24}{}'.format('#','Time','Time Difference', 'Port','Event Summary')) 62 | print('-'*175) 63 | 64 | eventdict = {} 65 | for num,event in enumerate(result,1): 66 | if event.get('eventRecord'): 67 | eventdescr = event['eventRecord']['attributes']['descr'].split() 68 | eventdescr = ' '.join(eventdescr) 69 | if len(eventdescr) > 120: 70 | summaryeventdescr = eventdescr[:120] + '...' 71 | else: 72 | summaryeventdescr = eventdescr 73 | eventcreated = ' '.join(event['eventRecord']['attributes']['created'].split('T')) 74 | eventtrig = event['eventRecord']['attributes']['trig'] 75 | eventuser = event['eventRecord']['attributes']['user'] 76 | eventdn = event['eventRecord']['attributes']['dn'] 77 | #if 'Port' in summaryeventdescr and 'po' in eventdn: 78 | #print(eventdn) 79 | if 'eth' in eventdn and not 'extpaths' in eventdn: 80 | # print(1) 81 | leaf = re.search(r'(node-[0-9]{1,3})|(paths-[0-9]{1,3})', eventdn).group() 82 | if leaf.startswith('paths'): 83 | leaf = leaf.replace('paths', 'leaf') 84 | if leaf.startswith('node'): 85 | leaf = leaf.replace('node', 'leaf') 86 | interface = re.search(r'eth.*\/[0-9]{1,3}\]', eventdn).group() 87 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 88 | elif re.search(r'po[0-9]*\]', eventdn): 89 | # print(2) 90 | leaf = re.search(r'node-[0-9]{1,3}', eventdn).group() 91 | leaf = leaf.replace('node', 'leaf') 92 | interface = re.search(r'po[0-9]*\]', eventdn).group() 93 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 94 | #elif 'rsoosPath' in eventdn and not 'extpaths' in eventdn: 95 | # print(3) 96 | # #print(eventdn) 97 | # leaf = re.search(r'protpaths-[0-9]{3}-[0-9]{3}', eventdn).group() 98 | # leaf = leaf.replace('protpaths', 'VPC node') 99 | # interface = re.search(r'pathep-.*\]', eventdn).group() 100 | # interface = interface.replace('pathep-', "") 101 | # portinterfaces = '{} {}'.format(leaf,interface[:-1]) 102 | #elif 'rsoosPath' in eventdn and 'extpaths' in eventdn: 103 | # print(4) 104 | # leaf = re.search(r'paths-[0-9]{3}', eventdn).group() 105 | # leaf = leaf.replace('paths','node') 106 | # fex = re.search(r'extpaths-.*\]', eventdn).group() 107 | # interface = re.search(r'eth[0-9]{1,3}/[0-9]{1,3}', eventdn).group() 108 | # portinterfaces = '{} {} {}'.format(leaf,fex,interface) 109 | else: 110 | portinterfaces = "" 111 | diff_time = time_difference(eventcreated[:-6]) 112 | eventdict[num] = [eventcreated[:-6],eventtrig,eventuser,eventdn,eventdescr] 113 | print('{:5}.) {:26}{:20}{:24}{}'.format(num,eventcreated[:-6],diff_time,portinterfaces,summaryeventdescr)) 114 | 115 | while True: 116 | moredetails = raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 117 | if moredetails == '': 118 | break 119 | if moredetails.isdigit() and eventdict.get(int(moredetails)): 120 | break 121 | else: 122 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 123 | if moredetails == '': 124 | continue 125 | diff_time = time_difference(eventdict[int(moredetails)][0]) 126 | print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected')) 127 | print('-'*120) 128 | #print('/'.join(str(eventdict[int(moredetails)][3]).split('/')[:-1])) 129 | print('{:26}{:20}{:18}{:18}{}\n'.format(eventdict[int(moredetails)][0],diff_time, eventdict[int(moredetails)][1],eventdict[int(moredetails)][2],'/'.join(str(eventdict[int(moredetails)][3]).split('/')[:-1]))) 130 | print('Event Details') 131 | print('-'*15) 132 | print(eventdict[int(moredetails)][4]) 133 | print('\n\n') 134 | 135 | refresh = askrefresh() 136 | if refresh == True: 137 | continue 138 | else: 139 | print('\nEnding Program...\n') 140 | break 141 | 142 | 143 | def main(): 144 | gatheranddisplayrecentevents() 145 | 146 | 147 | if __name__ == '__main__': 148 | try: 149 | main() 150 | except KeyboardInterrupt as k: 151 | print("\n\nExiting Program....") 152 | exit() 153 | except Exception as e: 154 | print(e) 155 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/multissh.py: -------------------------------------------------------------------------------- 1 | from multiprocessing.dummy import Pool as ThreadPool 2 | import paramiko 3 | import logging 4 | import time 5 | logging.basicConfig(level=logging.INFO) 6 | 7 | switchlist = [#("10.200.200.203","cisco","cisco"), 8 | ##("10.200.200.204","cisco","cislco"), 9 | #("10.200.200.205","cisco","cisco"), 10 | #("10.200.200.206","cisco","cisco"), 11 | ## ("10.200.200.208","cisco","cisco"), 12 | #("10.200.200.205","cisco","cisco"), 13 | #("10.200.200.206","cisco","cisco"), 14 | #("10.200.200.205","cisco","cisco"), 15 | #("10.200.200.206","cisco","cisco"), 16 | ("192.168.255.1","cisco","cisco"), 17 | # ("10.200.200.205","cisco","cisco"), 18 | #("10.200.200.206","cisco","cisco"), 19 | #("10.200.200.208","cisco","cisco"), 20 | #("10.200.200.209","cisco","cisco"), 21 | #("10.200.200.210","cisco","cisco"), 22 | ] 23 | 24 | class ssh: 25 | 26 | def __init__(self, address, username, password): 27 | print("Connecting to server on ip", str(address) + ".") 28 | self.client = paramiko.SSHClient() 29 | self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 30 | self.client.connect(address, username=username, password=password, look_for_keys=False) 31 | # self.transport = paramiko.Transport((address, 22)) 32 | #self.session = self.transport.open_channel(kind='session') 33 | #self.session.setblocking(0) 34 | #print('hit1') 35 | #self.transport.connect(username=username, password=password) 36 | #print('connected') 37 | 38 | # thread = threading.Thread(target=self.process) 39 | # thread.daemon = Truec 40 | # thread.start() 41 | 42 | def closeConnection(self): 43 | if(self.client != None): 44 | self.client.close() 45 | self.transport.close() 46 | def sendcommand(self): 47 | print('hit2') 48 | self.session.send('show run\r') 49 | result = self.session.recv(9000) 50 | print(result) 51 | 52 | def openShell(self): 53 | self.shell = self.client.invoke_shell() 54 | 55 | def sendShell(self, command): 56 | if(self.shell): 57 | self.shell.send(command + "\n") 58 | else: 59 | print("Shell not opened.") 60 | 61 | def create_switchobj(switch): 62 | sshobj = ssh(switch[0],switch[1],switch[2]) 63 | #import pdb; pdb.set_trace() 64 | print('CONNECTED' + switch[0]) 65 | shell = sshobj.client.invoke_shell() 66 | while True: 67 | if shell.recv_ready(): 68 | break 69 | output = shell.recv(5000) 70 | shell.send('show run\n') 71 | print(shell.recv_ready(),1) 72 | #time.sleep(1) 73 | print(shell.recv_ready(),2) 74 | #import pdb; pdb.set_trace() 75 | while True: 76 | if shell.recv_ready(): 77 | output += shell.recv(5000) 78 | time.sleep(10) 79 | elif not shell.recv_ready(): 80 | break 81 | #while True: 82 | # current = None 83 | # current = shell.recv(5000) 84 | # import pdb; pdb.set_trace() 85 | # if current != None: 86 | # output += current 87 | # else: 88 | # break 89 | # print(repr(current)) 90 | #break 91 | 92 | #import pdb; pdb.set_trace() 93 | if 'ERROR' in output: 94 | print('\t\t\t\t\t\t' +switch[0]) 95 | print(output) 96 | 97 | #def sendcommand_func(switchobj): 98 | # switchobj.sendcommand() 99 | 100 | def multithreading_kickoff(switchlist): 101 | pool = ThreadPool(10) 102 | results = pool.map(lambda x : create_switchobj(x), switchlist) 103 | pool.close() 104 | pool.join() 105 | 106 | 107 | def main(): 108 | a = time.time() 109 | #switchlistobj = [] 110 | #for switch in switchlist: 111 | # sshobj = create_switchobj(switch) 112 | # switchlistobj.append(sshobj) 113 | #for switch in switchlist: 114 | # create_switchobj(switch) 115 | 116 | multithreading_kickoff(switchlist) 117 | b = time.time() 118 | print(b-a) 119 | 120 | main() 121 | 122 | 123 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/routing.py: -------------------------------------------------------------------------------- 1 | import re 2 | import readline 3 | import urllib2 4 | import json 5 | import ssl 6 | import os 7 | import datetime 8 | 9 | def displaycurrenttime(): 10 | currenttime = datetime.datetime.now() 11 | return str(currenttime)[:-3] 12 | 13 | def time_difference(fault_time): 14 | currenttime = datetime.datetime.now() 15 | ref_fault_time = datetime.datetime.strptime(fault_time, '%Y-%m-%d %H:%M:%S.%f') 16 | return str(currenttime - ref_fault_time)[:-7] 17 | 18 | 19 | def GetRequest(url, icookie): 20 | method = "GET" 21 | cookies = 'APIC-cookie=' + icookie 22 | request = urllib2.Request(url) 23 | request.add_header("cookie", cookies) 24 | request.add_header("Content-Type", "application/json") 25 | request.add_header('Accept', 'application/json') 26 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 27 | def GetResponseData(url): 28 | response = GetRequest(url, cookie) 29 | result = json.loads(response.read()) 30 | return result['imdata'], result["totalCount"] 31 | 32 | def getCookie(): 33 | global cookie 34 | with open('/.aci/.sessions/.token', 'r') as f: 35 | cookie = f.read() 36 | 37 | 38 | def askrefresh(): 39 | while True: 40 | refresh = raw_input("Return to fault list? [y=default|n]: ") or 'y' 41 | if refresh[0].lower() == 'y': 42 | return True 43 | elif refresh[0].lower() == 'n': 44 | return False 45 | else: 46 | continue 47 | 48 | 49 | def gatheranddisplayrecentfaults(): 50 | while True: 51 | getCookie() 52 | os.system('clear') 53 | print("Current time = " + displaycurrenttime()) 54 | url = """https://localhost/api/node/class/uribv4Route.json?rsp-subtree=full""" 55 | #result, totalcount = GetResponseData(url) 56 | #url2 ="""https://localhost/api/node/mo/topology/pod-1/node-101/sys/uribv4/dom-SI:SI/db-rt/rt-[0.0.0.0/0].json?query-target=children&target-subtree-class=uribv4Nexthop&query-target-filter=not(wcard(uribv4Nexthop.dn,%22__ui_%22))""" 57 | #print(result) 58 | #print(result) 59 | result, totalcount = GetResponseData(url) 60 | print('done') 61 | #print(result) 62 | break 63 | 64 | # faultdict = {} 65 | # for num,fault in enumerate(result,1): 66 | # if fault.get('faultInst'): 67 | # faultdescr = fault['faultInst']['attributes']['descr'].split() 68 | # faultdescr = ' '.join(faultdescr) 69 | # if len(faultdescr) > 120: 70 | # summaryfaultdescr = faultdescr[:120] + '...' 71 | # else: 72 | # summaryfaultdescr = faultdescr 73 | # faultlastTransition = ' '.join(fault['faultInst']['attributes']['lastTransition'].split('T')) 74 | # faulttype = fault['faultInst']['attributes']['type'] 75 | # faultstate = fault['faultInst']['attributes']['lc'] 76 | # faultdn = fault['faultInst']['attributes']['dn'] 77 | # #print(faultlastTransition) 78 | # diff_time = time_difference(faultlastTransition[:-6]) 79 | # faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 80 | # print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 81 | # else: 82 | # faultdescr = fault['faultDelegate']['attributes']['descr'].split() 83 | # faultdescr = ' '.join(faultdescr) 84 | # if len(faultdescr) > 120: 85 | # summaryfaultdescr = faultdescr[:120] + '...' 86 | # else: 87 | # summaryfaultdescr = faultdescr 88 | # faultlastTransition = ' '.join(fault['faultDelegate']['attributes']['lastTransition'].split('T')) 89 | # faulttype = fault['faultDelegate']['attributes']['type'] 90 | # faultstate = fault['faultDelegate']['attributes']['lc'] 91 | # faultdn = fault['faultDelegate']['attributes']['dn'] 92 | # diff_time = time_difference(faultlastTransition[:-6]) 93 | # faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 94 | # print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 95 | # 96 | # 97 | # while True: 98 | # moredetails = raw_input("\nMore details, select number: ") 99 | # if moredetails.isdigit() and faultdict.get(int(moredetails)): 100 | # break 101 | # else: 102 | # print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 103 | # diff_time = time_difference(faultdict[int(moredetails)][0]) 104 | # print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','Fault-State','Object-Affected')) 105 | # print('-'*120) 106 | # #print('/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1])) 107 | # print('{:26}{:20}{:18}{:18}{}\n'.format(faultdict[int(moredetails)][0],diff_time, faultdict[int(moredetails)][1],faultdict[int(moredetails)][2],'/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1]))) 108 | # print('Fault Details') 109 | # print('-'*15) 110 | # print(faultdict[int(moredetails)][4]) 111 | # print('\n\n') 112 | # 113 | # refresh = askrefresh() 114 | # if refresh == True: 115 | # continue 116 | # else: 117 | # print('\nEnding Program...\n') 118 | # break 119 | 120 | 121 | def main(): 122 | gatheranddisplayrecentfaults() 123 | 124 | 125 | if __name__ == '__main__': 126 | main() -------------------------------------------------------------------------------- /misc_unfinished_scripts/show_all_endpoints_on_interface.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib2 6 | import json 7 | import ssl 8 | import ipaddress 9 | 10 | 11 | def GetRequest(url, icookie): 12 | method = "GET" 13 | cookies = 'APIC-cookie=' + icookie 14 | request = urllib2.Request(url) 15 | request.add_header("cookie", cookies) 16 | request.add_header("Content-Type", "application/json") 17 | request.add_header('Accept', 'application/json') 18 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 19 | def GetResponseData(url): 20 | response = GetRequest(url, cookie) 21 | result = json.loads(response.read()) 22 | return result['imdata'], result["totalCount"] 23 | 24 | class fvCEp(): 25 | def __init__(self, mac=None, name=None, encap=None, 26 | lcC=None, dn=None, fvRsVm=None, fvRsHyper=None, 27 | fvRsCEpToPathEp=None, ip=None, fvIplist=[]): 28 | self.mac = mac 29 | self.name = name 30 | self.encap = encap 31 | self.dn = dn 32 | self.lcC = lcC 33 | self.fvRsVm = fvRsVm 34 | self.fvRsHyper = fvRsHyper 35 | self.ip = ip 36 | #self.iplist = iplist 37 | self.fvIplist = fvIplist 38 | self.fvRsCEpToPathEp = fvRsCEpToPathEp 39 | def __repr__(self): 40 | return self.dn 41 | def __getitem__(self, mac): 42 | if mac in self.mac: 43 | return self.mac 44 | else: 45 | return None 46 | def showips(self): 47 | iplist = [fvIP.addr for fvIP in self.fvIplist] 48 | return ', '.join(iplist) 49 | 50 | 51 | class fvIp(): 52 | def __init__(self, addr=None, rn=None,fvReportingNodes=None): 53 | self.addr = addr 54 | self.rn = rn 55 | self.fvReportingNodes = fvReportingNodes 56 | def __repr__(self): 57 | return self.addr 58 | def __getitem__(self, addr): 59 | if addr in self.addr: 60 | return self.addr 61 | else: 62 | return None 63 | 64 | class fvRsCEpToPathEp(): 65 | def __init__(self, tDn=None, lcC=None, fvReportingNodes=[], forceResolve=None): 66 | self.lcC = lcC #shows location it learned if 'vmm' vmm knows it cause vmware, 'vmm,learned' means vmware and switch knows, if just 'learned' not vmm source 67 | self.tDn = tDn # location of learned interface "topology/pod-1/paths-102/extpaths-112/pathep-[eth1/25]" example 68 | self.fvReportingNodes = fvReportingNodes # looks like port-channels use fvReportingNode api class (describes leafs where ep is discovered) 69 | self.forceResolve = forceResolve 70 | def __repr__(self): 71 | return self.tDn 72 | 73 | class fvRsVm(): 74 | def __init__(self, state=None, tDn=None, dn=None): 75 | self.state = state 76 | self.dn = dn 77 | self.tDn = tDn #internal vm name to lookup vmware vm name 78 | def __repr__(self): 79 | return self.tDn 80 | 81 | class fvRsHyper(): 82 | def __init__(self, state=None, tDn=None): 83 | self.state = state 84 | self.tDn = tDn #hyperviser internal name to look up vmware host name 85 | def __repr__(self): 86 | return self.tDn 87 | 88 | def get_Cookie(): 89 | global cookie 90 | with open('/.aci/.sessions/.token', 'r') as f: 91 | cookie = f.read() 92 | 93 | 94 | def gather_fvCEp_fullinfo(result): 95 | eplist = [] 96 | fvRsVmobject = None 97 | fvRsCEpToPathEpobject = None 98 | fvRsHyperobject = None 99 | fvIplist = [] 100 | for ep in result: 101 | fvReportingNodes = [] 102 | mac = ep['fvCEp']['attributes']['mac'] 103 | name = ep['fvCEp']['attributes']['name'] 104 | encap = ep['fvCEp']['attributes']['encap'] 105 | lcC = ep['fvCEp']['attributes']['lcC'] 106 | dn = ep['fvCEp']['attributes']['dn'] 107 | ip = ep['fvCEp']['attributes']['ip'] 108 | if ep['fvCEp'].get('children'): 109 | for ceptopath in ep['fvCEp']['children']: 110 | if ceptopath.get('fvRsCEpToPathEp') and ceptopath['fvRsCEpToPathEp']['attributes']['state'] == 'formed': 111 | fvRsCEpToPathEp_tDn = ceptopath['fvRsCEpToPathEp']['attributes']['tDn'] 112 | fvRsCEpToPathEp_lcC = ceptopath['fvRsCEpToPathEp']['attributes']['lcC'] 113 | fvRsCEpToPathEp_forceResolve = ceptopath['fvRsCEpToPathEp']['attributes']['forceResolve'] 114 | fvRsCEpToPathEpobject = fvRsCEpToPathEp(forceResolve=fvRsCEpToPathEp_forceResolve, 115 | tDn=fvRsCEpToPathEp_tDn, lcC=fvRsCEpToPathEp_lcC) 116 | elif ceptopath.get('fvIp'): 117 | fvIp_addr = ceptopath['fvIp']['attributes']['addr'] 118 | fvIp_rn = ceptopath['fvIp']['attributes']['rn'] 119 | if ceptopath['fvIp'].get('children'): 120 | fvReportingNodes = [node['fvReportingNode']['attributes']['rn'] for node in ceptopath['fvIp']['children']] 121 | else: 122 | fvReportingNodes = None 123 | fvIplist.append(fvIp(addr=fvIp_addr, rn=fvIp_rn, 124 | fvReportingNodes=fvReportingNodes)) 125 | elif ceptopath.get('fvRsVm') and ceptopath['fvRsVm']['attributes']['state'] == 'formed': 126 | fvRsVm_state = ceptopath['fvRsVm']['attributes']['state'] 127 | fvRsVm_tDn = ceptopath['fvRsVm']['attributes']['tDn'] 128 | fvRsVmobject = fvRsVm(state=fvRsVm_state, 129 | tDn=fvRsVm_tDn) 130 | elif ceptopath.get('fvRsHyper') and ceptopath['fvRsHyper']['attributes']['state'] == 'formed': 131 | fvRsHyper_state = ceptopath['fvRsHyper']['attributes']['state'] 132 | fvRsHyper_tDn = ceptopath['fvRsHyper']['attributes']['tDn'] 133 | fvRsHyperobject = fvRsHyper(state=fvRsHyper_state, 134 | tDn=fvRsHyper_tDn) 135 | eplist.append(fvCEp(mac=mac, name=name, encap=encap, 136 | lcC=lcC, dn=dn, fvRsVm=fvRsVmobject, fvRsCEpToPathEp=fvRsCEpToPathEpobject, 137 | ip=ip, fvRsHyper=fvRsHyperobject, fvIplist=fvIplist)) 138 | fvIplist = [] 139 | return eplist 140 | 141 | 142 | def mac_path_function(): 143 | url = """https://localhost/api/node/class/fvCEp.json?rsp-subtree=full&target-subtree-class=fvCEp,fvRsCEpToPathEp""" 144 | result, totalcount = GetResponseData(url) 145 | fvCEplist = gather_fvCEp_fullinfo(result) 146 | #print(fvCEplist) 147 | for x in fvCEplist: 148 | #print("{:25}{:20}{:20}{}".format(x.mac, x.ip, x.fvIplist, x.fvRsCEpToPathEp)) 149 | print("{},{},{},{}".format(x.mac,x.ip,x.fvIplist,x.fvRsCEpToPathEp)) 150 | print(totalcount) 151 | #for fvCEp in fvCEplist: 152 | # result, totalcount = GetResponseData(url) 153 | # completefvCEplist = gather_fvCEp_fullinfo(result) 154 | # #print(completefvCEplist) 155 | # #Display current endpoint info 156 | # 157 | # find_current_ep_info(completefvCEplist[0], totalcount) 158 | # #Display current known endpoint history 159 | # display_live_history_info(completefvCEplist[0], totalcount) 160 | 161 | 162 | def main(): 163 | get_Cookie() 164 | mac_path_function() 165 | 166 | if __name__ == '__main__': 167 | main() 168 | -------------------------------------------------------------------------------- /misc_unfinished_scripts/urlib.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | import readline 3 | import urllib2 4 | import json 5 | import base64 6 | import ssl 7 | import getpass 8 | import os 9 | 10 | os.system('clear') 11 | 12 | username = raw_input('username: ') 13 | password = getpass.getpass('(Backspace not supported...blame APIC terminal)\npassword: ') 14 | print(password) 15 | 16 | def addingmultipleheaders(items,request): 17 | if type(items) == list: 18 | for x, y in items: 19 | request.add_header(x,y) 20 | 21 | def GetRequest(url): 22 | method = "GET" 23 | request = urllib2.Request(url) 24 | request.add_header("Content-Type", "application/json") 25 | request.add_header('Accept', 'application/json') 26 | #addingmultipleheaders([("Content-Type", "application/json"),('Accept', 'application/json')], request) 27 | base64string = base64.b64encode('%s:%s' % (str(username), str(password))) 28 | request.add_header("Authorization", "Basic %s" % base64string) 29 | return urllib2.urlopen(request, context=ssl._create_unverified_context()) 30 | 31 | 32 | url = 'https://10.100.100.29:9060/ers/config/endpoint' #.format(endpointmac) 33 | response = GetRequest(url) 34 | 35 | print('\r') 36 | endpointmac = str(raw_input('Last 4 of MAC? : ')) 37 | print('\r') 38 | #convert any mac combination (. or :) to API acceptiable MAC format 39 | if '.' in endpointmac or ':' in endpointmac: 40 | endpointmac.replace('.', '').replace(':', '') 41 | endpointmac = ':'.join(endpointmac[i:i+2] for i in range(0, len(endpointmac), 2)) 42 | endpointmac = endpointmac.upper() 43 | 44 | # 45 | #url = 'https://10.100.100.29:9060/ers/config/endpoint' #.format(endpointmac) 46 | #response = GetRequest(url) 47 | if response: 48 | possiblematches = [] 49 | matchdic = {} 50 | getendpointresult = json.loads(response.read()) 51 | for idfound in getendpointresult['SearchResult']['resources']: 52 | if endpointmac in idfound['name']: 53 | possiblematches.append(idfound['name']) 54 | if possiblematches: 55 | #print('\n') 56 | print("Found Possible MACs:") 57 | #matchdic = {} 58 | #start = 0 59 | for num, mac in enumerate(possiblematches, 1): 60 | matchdic[num] = mac 61 | print('\t' + str(num) + '.) ' + mac) 62 | else: 63 | print('No matches found') 64 | # print('\n') 65 | # print('***********************') 66 | # print('Available Groups:') 67 | if len(possiblematches) == 1: 68 | endpointmac = possiblematches[0] 69 | elif len(possiblematches) > 1: 70 | print('\r') 71 | numberselected = int(raw_input('Select MAC address #: ')) 72 | endpointmac = matchdic[numberselected] 73 | else: 74 | print("No Matches found") 75 | print('\r') 76 | print('Available Groups:') 77 | print('***********************') 78 | 79 | url = 'https://10.100.100.29:9060/ers/config/endpoint/name/{}'.format(endpointmac) 80 | response = GetRequest(url) 81 | if response: 82 | getendpointresult = json.loads(response.read()) 83 | endpointid = getendpointresult['ERSEndPoint']['id'] 84 | 85 | 86 | url = 'https://10.100.100.29:9060/ers/config/endpointgroup' 87 | response = GetRequest(url) 88 | if response: 89 | #print(response.read()) 90 | groupdic = {} 91 | allgroupresult = json.loads(response.read()) 92 | listofgroups = allgroupresult['SearchResult']['resources'] 93 | for num, group in enumerate(listofgroups, 1): 94 | print('\t' + str(num) + '.) ' + group['name']) 95 | groupdic[num] = group['name'] 96 | 97 | 98 | print('\r') 99 | desiredgroup = int(raw_input('What is new Endpoint Group?: ')) 100 | #print(desiredgroup) 101 | #desiredgroup = str(groupdic[desiredgroup]) 102 | #print(desiredgroup) 103 | url = 'https://10.100.100.29:9060/ers/config/endpointgroup/name/{}'.format(groupdic[desiredgroup]) 104 | 105 | response = GetRequest(url) 106 | if response: 107 | endgroupresult = json.loads(response.read()) 108 | endpointgroupid = endgroupresult['EndPointGroup']['id'] 109 | 110 | 111 | 112 | url = "https://10.100.100.27:9060/ers/config/endpoint/{}".format(endpointid) 113 | data = json.dumps({"ERSEndPoint": {"groupId": endpointgroupid, "staticGroupAssignment": True}}) 114 | method = "PUT" 115 | request = urllib2.Request(url, data) 116 | addingmultipleheaders([("Content-Type", "application/json"),('Accept', 'application/json')], request) 117 | base64string = base64.b64encode('%s:%s' % (str(username), str(password))) 118 | request.add_header("Authorization", "Basic %s" % base64string) 119 | request.get_method = lambda: method 120 | #if data: request.add_data(data) 121 | response = urllib2.urlopen(request, context=ssl._create_unverified_context()) 122 | if response: 123 | responseoutput = response.read() 124 | if responseoutput == '{\n "UpdatedFieldsList" : {\n "updatedField" : [ ]\n }\n}': 125 | print("""\n(INFO) MAC already using """ + groupdic[desiredgroup] + '\n') 126 | else: 127 | if response.getcode() == 200: 128 | print("\nSuccess: Endpoint updated to " + groupdic[desiredgroup] + "\n") 129 | #print(response.getcode()) 130 | #print(responseoutput) 131 | -------------------------------------------------------------------------------- /python3_migration/configuration/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/python3_migration/configuration/__init__.py -------------------------------------------------------------------------------- /python3_migration/faults_and_logs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/python3_migration/faults_and_logs/__init__.py -------------------------------------------------------------------------------- /python3_migration/faults_and_logs/most_recent_admin_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib.request, urllib.error, urllib.parse 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | from localutils.custom_utils import * 14 | 15 | 16 | 17 | def askrefresh(): 18 | while True: 19 | refresh = custom_raw_input("Return to admin list? [y=default|n]: ") or 'y' 20 | if refresh[0].lower() == 'y': 21 | return True 22 | elif refresh[0].lower() == 'n': 23 | return False 24 | else: 25 | continue 26 | 27 | 28 | def gatheranddisplayrecentadmins(): 29 | while True: 30 | #getCookie() 31 | clear_screen() 32 | print(("Current time = " + displaycurrenttime())) 33 | url = """https://{apic}/api/node/class/aaaModLR.json?query-target-filter=not(wcard(aaaModLR.dn,%22__ui_%22))&order-by=aaaModLR.created|desc&page=0&page-size=50""".format(apic=apic) 34 | result, totauserount = GetResponseData(url, cookie) 35 | print(('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','User','admin Summary'))) 36 | print(('-'*175)) 37 | admindict = {} 38 | for num,admin in enumerate(result,1): 39 | if admin.get('aaaModLR'): 40 | admindescr = admin['aaaModLR']['attributes']['descr'].split() 41 | admindescr = ' '.join(admindescr) 42 | if len(admindescr) > 120: 43 | summaryadmindescr = admindescr[:120] + '...' 44 | else: 45 | summaryadmindescr = admindescr 46 | admincreated = ' '.join(admin['aaaModLR']['attributes']['created'].split('T')) 47 | admintrig = admin['aaaModLR']['attributes']['trig'] 48 | adminuser = admin['aaaModLR']['attributes']['user'] 49 | admindn = admin['aaaModLR']['attributes']['dn'] 50 | diff_time = time_difference(admincreated[:-6]) 51 | admindict[num] = [admincreated[:-6],admintrig,adminuser,admindn,admindescr] 52 | print(('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,admincreated[:-6],diff_time,admintrig,adminuser,summaryadmindescr))) 53 | 54 | while True: 55 | moredetails = custom_raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 56 | if moredetails == '': 57 | break 58 | if moredetails.isdigit() and admindict.get(int(moredetails)): 59 | break 60 | else: 61 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 62 | if moredetails == '': 63 | continue 64 | diff_time = time_difference(admindict[int(moredetails)][0]) 65 | print(('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected'))) 66 | print(('-'*120)) 67 | print(('{:26}{:20}{:18}{:18}{}\n'.format(admindict[int(moredetails)][0],diff_time, admindict[int(moredetails)][1],admindict[int(moredetails)][2],'/'.join(str(admindict[int(moredetails)][3]).split('/')[:-1])))) 68 | print('admin Details') 69 | print(('-'*15)) 70 | print((admindict[int(moredetails)][4])) 71 | print('\n\n') 72 | 73 | refresh = askrefresh() 74 | if refresh == True: 75 | continue 76 | else: 77 | print('\nEnding Program...\n') 78 | break 79 | 80 | 81 | 82 | def main(import_apic,import_cookie): 83 | global apic 84 | global cookie 85 | cookie = import_cookie 86 | apic = import_apic 87 | gatheranddisplayrecentadmins() 88 | 89 | 90 | if __name__ == '__main__': 91 | try: 92 | main() 93 | except KeyboardInterrupt as k: 94 | print("\n\nExiting Program....") 95 | exit() 96 | -------------------------------------------------------------------------------- /python3_migration/faults_and_logs/most_recent_event_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib.request, urllib.error, urllib.parse 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | from localutils.custom_utils import * 14 | 15 | 16 | def GetRequest(url, icookie): 17 | method = "GET" 18 | cookies = 'APIC-cookie=' + icookie 19 | request = urllib.request.Request(url) 20 | request.add_header("cookie", cookies) 21 | request.add_header("Content-trig", "application/json") 22 | request.add_header('Accept', 'application/json') 23 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 24 | def GetResponseData(url): 25 | response = GetRequest(url, cookie) 26 | result = json.loads(response.read()) 27 | return result['imdata'], result["totalCount"] 28 | 29 | #def getCookie(): 30 | # global cookie 31 | # with open('/.aci/.sessions/.token', 'r') as f: 32 | # cookie = f.read() 33 | 34 | def displaycurrenttime(): 35 | currenttime = datetime.datetime.now() 36 | return str(currenttime)[:-3] 37 | 38 | def time_difference(event_time): 39 | currenttime = datetime.datetime.now() 40 | ref_event_time = datetime.datetime.strptime(event_time, '%Y-%m-%d %H:%M:%S.%f') 41 | return str(currenttime - ref_event_time)[:-7] 42 | 43 | def askrefresh(): 44 | while True: 45 | refresh = custom_raw_input("Return to event list? [y=default|n]: ") or 'y' 46 | if refresh[0].lower() == 'y': 47 | return True 48 | elif refresh[0].lower() == 'n': 49 | return False 50 | else: 51 | continue 52 | 53 | 54 | def gatheranddisplayrecentevents(): 55 | while True: 56 | #getCookie() 57 | clear_screen() 58 | print(("Current time = " + displaycurrenttime())) 59 | print("\nEvents loading...\n") 60 | url = """https://{apic}/api/node/class/eventRecord.json?query-target-filter=not(wcard(eventRecord.dn,%22__ui_%22))&order-by=eventRecord.created|desc&page=0&page-size=50""".format(apic=apic) 61 | result, totalcount = GetResponseData(url) 62 | clear_screen() 63 | print(("Current time = " + displaycurrenttime())) 64 | print(('\n{:>5} {:26}{:20}{:24}{}'.format('#','Time','Time Difference', 'Port','Event Summary'))) 65 | print(('-'*175)) 66 | eventdict = {} 67 | for num,event in enumerate(result,1): 68 | if event.get('eventRecord'): 69 | eventdescr = event['eventRecord']['attributes']['descr'].split() 70 | eventdescr = ' '.join(eventdescr) 71 | if len(eventdescr) > 120: 72 | summaryeventdescr = eventdescr[:120] + '...' 73 | else: 74 | summaryeventdescr = eventdescr 75 | eventcreated = ' '.join(event['eventRecord']['attributes']['created'].split('T')) 76 | eventtrig = event['eventRecord']['attributes']['trig'] 77 | eventuser = event['eventRecord']['attributes']['user'] 78 | eventdn = event['eventRecord']['attributes']['dn'] 79 | if 'eth' in eventdn and not 'extpaths' in eventdn: 80 | leaf = re.search(r'(node-[0-9]{1,3})|(paths-[0-9]{1,3})', eventdn).group() 81 | if leaf.startswith('paths'): 82 | leaf = leaf.replace('paths', 'leaf') 83 | elif leaf.startswith('node'): 84 | leaf = leaf.replace('node', 'leaf') 85 | interface = re.search(r'eth.*\/[0-9]{1,3}\]', eventdn).group() 86 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 87 | elif re.search(r'po[0-9]*\]', eventdn): 88 | leaf = re.search(r'node-[0-9]{1,3}', eventdn).group() 89 | leaf = leaf.replace('node', 'leaf') 90 | interface = re.search(r'po[0-9]*\]', eventdn).group() 91 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 92 | #elif 'rsoosPath' in eventdn and not 'extpaths' in eventdn: 93 | # leaf = re.search(r'protpaths-[0-9]{3}-[0-9]{3}', eventdn).group() 94 | # leaf = leaf.replace('protpaths', 'VPC node') 95 | # interface = re.search(r'pathep-.*\]', eventdn).group() 96 | # interface = interface.replace('pathep-', "") 97 | # portinterfaces = '{} {}'.format(leaf,interface[:-1]) 98 | #elif 'rsoosPath' in eventdn and 'extpaths' in eventdn: 99 | # leaf = re.search(r'paths-[0-9]{3}', eventdn).group() 100 | # leaf = leaf.replace('paths','node') 101 | # fex = re.search(r'extpaths-.*\]', eventdn).group() 102 | # interface = re.search(r'eth[0-9]{1,3}/[0-9]{1,3}', eventdn).group() 103 | # portinterfaces = '{} {} {}'.format(leaf,fex,interface) 104 | else: 105 | portinterfaces = "" 106 | diff_time = time_difference(eventcreated[:-6]) 107 | eventdict[num] = [eventcreated[:-6],eventtrig,eventuser,eventdn,eventdescr] 108 | print(('{:5}.) {:26}{:20}{:24}{}'.format(num,eventcreated[:-6],diff_time,portinterfaces,summaryeventdescr))) 109 | 110 | while True: 111 | moredetails = custom_raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 112 | if moredetails == '': 113 | break 114 | if moredetails.isdigit() and eventdict.get(int(moredetails)): 115 | break 116 | else: 117 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 118 | if moredetails == '': 119 | continue 120 | diff_time = time_difference(eventdict[int(moredetails)][0]) 121 | print(('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected'))) 122 | print(('-'*120)) 123 | print(('{:26}{:20}{:18}{:18}{}\n'.format(eventdict[int(moredetails)][0],diff_time, eventdict[int(moredetails)][1],eventdict[int(moredetails)][2],'/'.join(str(eventdict[int(moredetails)][3]).split('/')[:-1])))) 124 | print('Event Details') 125 | print(('-'*15)) 126 | print((eventdict[int(moredetails)][4])) 127 | print('\n\n') 128 | refresh = askrefresh() 129 | if refresh == True: 130 | continue 131 | else: 132 | print('\nEnding Program...\n') 133 | break 134 | 135 | 136 | def main(import_apic,import_cookie): 137 | global apic 138 | global cookie 139 | cookie = import_cookie 140 | apic = import_apic 141 | gatheranddisplayrecentevents() 142 | 143 | 144 | if __name__ == '__main__': 145 | try: 146 | main() 147 | except KeyboardInterrupt as k: 148 | print("\n\nExiting Program....") 149 | exit() 150 | -------------------------------------------------------------------------------- /python3_migration/faults_and_logs/most_recent_fault_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib.request, urllib.error, urllib.parse 9 | import json 10 | import ssl 11 | import os 12 | import datetime 13 | from localutils.custom_utils import * 14 | 15 | 16 | def GetRequest(url, icookie): 17 | method = "GET" 18 | cookies = 'APIC-cookie=' + icookie 19 | request = urllib.request.Request(url) 20 | request.add_header("cookie", cookies) 21 | request.add_header("Content-Type", "application/json") 22 | request.add_header('Accept', 'application/json') 23 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 24 | def GetResponseData(url): 25 | response = GetRequest(url, cookie) 26 | result = json.loads(response.read()) 27 | return result['imdata'], result["totalCount"] 28 | 29 | #def getCookie(): 30 | # global cookie 31 | # with open('/.aci/.sessions/.token', 'r') as f: 32 | # cookie = f.read() 33 | 34 | def displaycurrenttime(): 35 | currenttime = datetime.datetime.now() 36 | return str(currenttime)[:-3] 37 | 38 | def time_difference(fault_time): 39 | currenttime = datetime.datetime.now() 40 | ref_fault_time = datetime.datetime.strptime(fault_time, '%Y-%m-%d %H:%M:%S.%f') 41 | return str(currenttime - ref_fault_time)[:-7] 42 | 43 | 44 | def askrefresh(): 45 | while True: 46 | refresh = custom_raw_input("Return to fault list? [y=default|n]: ") or 'y' 47 | if refresh[0].lower() == 'y': 48 | return True 49 | elif refresh[0].lower() == 'n': 50 | return False 51 | else: 52 | continue 53 | 54 | 55 | def gatheranddisplayrecentfaults(): 56 | while True: 57 | #getCookie() 58 | clear_screen() 59 | print(("Current time = " + displaycurrenttime())) 60 | url = """https://{apic}/api/node/class/faultInfo.json?query-target-filter=and(ne(faultInfo.severity,"cleared"))&order-by=faultInfo.lastTransition|desc&page=0&page-size=100""".format(apic=apic) 61 | result, totalcount = GetResponseData(url) 62 | print(('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','Fault-State','Fault Summary'))) 63 | print(('-'*175)) 64 | faultdict = {} 65 | for num,fault in enumerate(result,1): 66 | if fault.get('faultInst'): 67 | faultdescr = fault['faultInst']['attributes']['descr'].split() 68 | faultdescr = ' '.join(faultdescr) 69 | if len(faultdescr) > 120: 70 | summaryfaultdescr = faultdescr[:112] + '...' 71 | else: 72 | summaryfaultdescr = faultdescr 73 | faultlastTransition = ' '.join(fault['faultInst']['attributes']['lastTransition'].split('T')) 74 | faulttype = fault['faultInst']['attributes']['type'] 75 | faultstate = fault['faultInst']['attributes']['lc'] 76 | faultdn = fault['faultInst']['attributes']['dn'] 77 | diff_time = time_difference(faultlastTransition[:-6]) 78 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 79 | print(('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr))) 80 | else: 81 | faultdescr = fault['faultDelegate']['attributes']['descr'].split() 82 | faultdescr = ' '.join(faultdescr) 83 | if len(faultdescr) > 120: 84 | summaryfaultdescr = faultdescr[:112] + '...' 85 | else: 86 | summaryfaultdescr = faultdescr 87 | faultlastTransition = ' '.join(fault['faultDelegate']['attributes']['lastTransition'].split('T')) 88 | faulttype = fault['faultDelegate']['attributes']['type'] 89 | faultstate = fault['faultDelegate']['attributes']['lc'] 90 | faultdn = fault['faultDelegate']['attributes']['dn'] 91 | diff_time = time_difference(faultlastTransition[:-6]) 92 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 93 | print(('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr))) 94 | while True: 95 | moredetails = custom_raw_input("\nMore details, select number [refresh=Blank and Enter]: ") 96 | if moredetails == '': 97 | break 98 | if moredetails.isdigit() and faultdict.get(int(moredetails)): 99 | break 100 | else: 101 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 102 | if moredetails == '': 103 | continue 104 | diff_time = time_difference(faultdict[int(moredetails)][0]) 105 | print(('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','Fault-State','Object-Affected'))) 106 | print(('-'*120)) 107 | print(('{:26}{:20}{:18}{:18}{}\n'.format(faultdict[int(moredetails)][0],diff_time, faultdict[int(moredetails)][1],faultdict[int(moredetails)][2],'/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1])))) 108 | print('Fault Details') 109 | print(('-'*15)) 110 | print((faultdict[int(moredetails)][4])) 111 | print('\n\n') 112 | refresh = askrefresh() 113 | if refresh == True: 114 | continue 115 | else: 116 | print('\nEnding Program...\n') 117 | break 118 | 119 | 120 | def main(import_apic,import_cookie): 121 | global apic 122 | global cookie 123 | cookie = import_cookie 124 | apic = import_apic 125 | gatheranddisplayrecentfaults() 126 | 127 | 128 | if __name__ == '__main__': 129 | try: 130 | main() 131 | except KeyboardInterrupt as k: 132 | print("\n\nExiting Program....") 133 | exit() 134 | -------------------------------------------------------------------------------- /python3_migration/information/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/python3_migration/information/__init__.py -------------------------------------------------------------------------------- /python3_migration/interfaces/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/python3_migration/interfaces/__init__.py -------------------------------------------------------------------------------- /python3_migration/interfaces/interfacedescriptioncreation.py: -------------------------------------------------------------------------------- 1 | Non -------------------------------------------------------------------------------- /python3_migration/interfaces/show_interface_epgs.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | #import re 4 | try: 5 | import readline 6 | except: 7 | pass 8 | import urllib.request, urllib.error, urllib.parse 9 | import json 10 | import ssl 11 | import os 12 | from localutils.custom_utils import * 13 | 14 | def GetRequest(url, icookie): 15 | method = "GET" 16 | cookies = 'APIC-cookie=' + icookie 17 | request = urllib.request.Request(url) 18 | request.add_header("cookie", cookies) 19 | request.add_header("Content-Type", "application/json") 20 | request.add_header('Accept', 'application/json') 21 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 22 | def GetResponseData(url): 23 | response = GetRequest(url, cookie) 24 | result = json.loads(response.read()) 25 | return result['imdata'], result["totalCount"] 26 | 27 | def retrieve_leaf_list(): 28 | # Display available leafs beginning of script 29 | url = """https://{apic}/api/node/mo/topology/pod-1.json?query-target=children&target-subtree-class=fabricNode&query-target-filter=and(wcard(fabricNode.id,"^1[0-9][0-9]"))""".format(apic=apic) 30 | result, totalcount = GetResponseData(url) 31 | #print(result) 32 | leafs = [leaf['fabricNode']['attributes']['id'] for leaf in result] 33 | #print('Available leafs to bounce ports...') 34 | return leafs 35 | 36 | def displayepgs(result): 37 | print(('\n{:10}{:15}{}'.format('Tenant','APP','EPG'))) 38 | print(('-'*40)) 39 | #print(result) 40 | if result[0]['l1PhysIf']['attributes']['layer'] == 'Layer3': 41 | print('Layer 3 interface, no EPGs\n') 42 | return 43 | if result[0]['l1PhysIf'].get('children'): 44 | for int in result[0]['l1PhysIf']['children']: 45 | for epgs in int['pconsCtrlrDeployCtx']['children']: 46 | epgpath = epgs['pconsResourceCtx']['attributes']['ctxDn'].split('/') 47 | #print(epgpath) 48 | tenant = epgpath[1][3:] 49 | app = epgpath[2][3:] 50 | epg = epgpath[3][4:] 51 | print(('{:10}{:15}{}'.format(tenant,app,epg))) 52 | print('\n') 53 | else: 54 | print('No Epgs found...\n') 55 | 56 | 57 | #with open('/.aci/.sessions/.token', 'r') as f: 58 | # cookie = f.read() 59 | 60 | def gatherandstoreinterfacesforleaf(leaf): 61 | url = """https://{apic}/api/node/class/topology/pod-1/node-101/l1PhysIf.json""".format(apic=apic) 62 | result, totalcount = GetResponseData(url) 63 | listofinterfaces = [interface['l1PhysIf']['attributes']['id'] for interface in result] 64 | return listofinterfaces 65 | 66 | def main(import_apic,import_cookie): 67 | global apic 68 | global cookie 69 | cookie = import_cookie 70 | apic = import_apic 71 | fex = False 72 | clear_screen() 73 | print(("\n1.) Physical interface\n" + 74 | "2.) Port-channel/vPC\n")) 75 | int_type = custom_raw_input("What is the interface type?: ") 76 | if int_type == '1': 77 | listleafs = retrieve_leaf_list() 78 | print(('\nAvailable Leafs\n' + '-'*12)) 79 | for leaf in sorted(listleafs): 80 | print(leaf)#Leaf' + ' Leaf'.join(leafs)) 81 | print('\r') 82 | while True: 83 | leaf = custom_raw_input("What is leaf number?: ") 84 | if leaf in listleafs: 85 | break 86 | else: 87 | print('\x1b[41;1mInvalid or leaf does not exist...try again\x1b[0m\n') 88 | availableinterfaces = gatherandstoreinterfacesforleaf(leaf) 89 | #while True: 90 | # askfex = raw_input("Fex interface? [y|n] (default=n): ") or 'n' 91 | # if askfex[0].lower() == 'y': 92 | # fex = True 93 | # break 94 | # else: 95 | # break 96 | while True: 97 | if fex == True: 98 | interface = custom_raw_input("What is the interface? (format: ethxxx/x/x): ") 99 | else: 100 | interface = custom_raw_input("What is the interface? (format: ethx/x): ") 101 | if interface in availableinterfaces: 102 | break 103 | else: 104 | print('\x1b[41;1mInvalid or interface does not exist...try again\x1b[0m\n') 105 | 106 | url = """https://{apic}/api/node/mo/topology/pod-1/node-{leaf}/sys/phys-[{interface}].json?rsp-subtree-include=full-deployment&target-node=all&target-path=l1EthIfToEPg""".format(leaf=leaf,interface=interface,apic=apic) 107 | #print(url) 108 | result, totalcount = GetResponseData(url) 109 | displayepgs(result) 110 | elif int_type == 2: 111 | pass 112 | else: 113 | pass 114 | 115 | 116 | 117 | if __name__ == '__main__': 118 | while True: 119 | main() 120 | ask = custom_raw_input('Another interface? [y|n]: ') or 'n' 121 | #print(ask) 122 | if ask[0].lower() == 'y': 123 | continue 124 | else: 125 | break 126 | 127 | 128 | 129 | -------------------------------------------------------------------------------- /python3_migration/localutils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/python3_migration/localutils/__init__.py -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/aci_health/most_recent_admin_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib.request.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-trig", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def displaycurrenttime(): 31 | currenttime = datetime.datetime.now() 32 | return str(currenttime)[:-3] 33 | 34 | def time_difference(admin_time): 35 | currenttime = datetime.datetime.now() 36 | ref_admin_time = datetime.datetime.strptime(admin_time, '%Y-%m-%d %H:%M:%S.%f') 37 | return str(currenttime - ref_admin_time)[:-7] 38 | 39 | 40 | def askrefresh(): 41 | while True: 42 | refresh = eval(input("Return to admin list? [y=default|n]: ")) or 'y' 43 | if refresh[0].lower() == 'y': 44 | return True 45 | elif refresh[0].lower() == 'n': 46 | return False 47 | else: 48 | continue 49 | 50 | 51 | def gatheranddisplayrecentadmins(): 52 | while True: 53 | getCookie() 54 | os.system('clear') 55 | print(("Current time = " + displaycurrenttime())) 56 | url = """https://localhost/api/node/class/aaaModLR.json?query-target-filter=not(wcard(aaaModLR.dn,%22__ui_%22))&order-by=aaaModLR.created|desc&page=0&page-size=50""" 57 | result, totauserount = GetResponseData(url) 58 | print(('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','User','admin Summary'))) 59 | print(('-'*175)) 60 | admindict = {} 61 | for num,admin in enumerate(result,1): 62 | if admin.get('aaaModLR'): 63 | admindescr = admin['aaaModLR']['attributes']['descr'].split() 64 | admindescr = ' '.join(admindescr) 65 | if len(admindescr) > 120: 66 | summaryadmindescr = admindescr[:120] + '...' 67 | else: 68 | summaryadmindescr = admindescr 69 | admincreated = ' '.join(admin['aaaModLR']['attributes']['created'].split('T')) 70 | admintrig = admin['aaaModLR']['attributes']['trig'] 71 | adminuser = admin['aaaModLR']['attributes']['user'] 72 | admindn = admin['aaaModLR']['attributes']['dn'] 73 | diff_time = time_difference(admincreated[:-6]) 74 | admindict[num] = [admincreated[:-6],admintrig,adminuser,admindn,admindescr] 75 | print(('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,admincreated[:-6],diff_time,admintrig,adminuser,summaryadmindescr))) 76 | 77 | while True: 78 | moredetails = eval(input("\nMore details, select number [refresh=Blank and Enter]: ")) 79 | if moredetails == '': 80 | break 81 | if moredetails.isdigit() and admindict.get(int(moredetails)): 82 | break 83 | else: 84 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 85 | if moredetails == '': 86 | continue 87 | diff_time = time_difference(admindict[int(moredetails)][0]) 88 | print(('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected'))) 89 | print(('-'*120)) 90 | print(('{:26}{:20}{:18}{:18}{}\n'.format(admindict[int(moredetails)][0],diff_time, admindict[int(moredetails)][1],admindict[int(moredetails)][2],'/'.join(str(admindict[int(moredetails)][3]).split('/')[:-1])))) 91 | print('admin Details') 92 | print(('-'*15)) 93 | print((admindict[int(moredetails)][4])) 94 | print('\n\n') 95 | 96 | refresh = askrefresh() 97 | if refresh == True: 98 | continue 99 | else: 100 | print('\nEnding Program...\n') 101 | break 102 | 103 | 104 | def main(): 105 | gatheranddisplayrecentadmins() 106 | 107 | 108 | if __name__ == '__main__': 109 | try: 110 | main() 111 | except KeyboardInterrupt as k: 112 | print("\n\nExiting Program....") 113 | exit() 114 | -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/aci_health/most_recent_event_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib.request.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-trig", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def displaycurrenttime(): 31 | currenttime = datetime.datetime.now() 32 | return str(currenttime)[:-3] 33 | 34 | def time_difference(event_time): 35 | currenttime = datetime.datetime.now() 36 | ref_event_time = datetime.datetime.strptime(event_time, '%Y-%m-%d %H:%M:%S.%f') 37 | return str(currenttime - ref_event_time)[:-7] 38 | 39 | def askrefresh(): 40 | while True: 41 | refresh = eval(input("Return to event list? [y=default|n]: ")) or 'y' 42 | if refresh[0].lower() == 'y': 43 | return True 44 | elif refresh[0].lower() == 'n': 45 | return False 46 | else: 47 | continue 48 | 49 | 50 | def gatheranddisplayrecentevents(): 51 | while True: 52 | getCookie() 53 | os.system('clear') 54 | print(("Current time = " + displaycurrenttime())) 55 | print("\nEvents loading...\n") 56 | url = """https://localhost/api/node/class/eventRecord.json?query-target-filter=not(wcard(eventRecord.dn,%22__ui_%22))&order-by=eventRecord.created|desc&page=0&page-size=50""" 57 | result, totalcount = GetResponseData(url) 58 | os.system('clear') 59 | print(("Current time = " + displaycurrenttime())) 60 | print(('\n{:>5} {:26}{:20}{:24}{}'.format('#','Time','Time Difference', 'Port','Event Summary'))) 61 | print(('-'*175)) 62 | eventdict = {} 63 | for num,event in enumerate(result,1): 64 | if event.get('eventRecord'): 65 | eventdescr = event['eventRecord']['attributes']['descr'].split() 66 | eventdescr = ' '.join(eventdescr) 67 | if len(eventdescr) > 120: 68 | summaryeventdescr = eventdescr[:120] + '...' 69 | else: 70 | summaryeventdescr = eventdescr 71 | eventcreated = ' '.join(event['eventRecord']['attributes']['created'].split('T')) 72 | eventtrig = event['eventRecord']['attributes']['trig'] 73 | eventuser = event['eventRecord']['attributes']['user'] 74 | eventdn = event['eventRecord']['attributes']['dn'] 75 | if 'eth' in eventdn and not 'extpaths' in eventdn: 76 | leaf = re.search(r'(node-[0-9]{1,3})|(paths-[0-9]{1,3})', eventdn).group() 77 | if leaf.startswith('paths'): 78 | leaf = leaf.replace('paths', 'leaf') 79 | elif leaf.startswith('node'): 80 | leaf = leaf.replace('node', 'leaf') 81 | interface = re.search(r'eth.*\/[0-9]{1,3}\]', eventdn).group() 82 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 83 | elif re.search(r'po[0-9]*\]', eventdn): 84 | leaf = re.search(r'node-[0-9]{1,3}', eventdn).group() 85 | leaf = leaf.replace('node', 'leaf') 86 | interface = re.search(r'po[0-9]*\]', eventdn).group() 87 | portinterfaces = '{} {}'.format(leaf,interface[:-1]) 88 | #elif 'rsoosPath' in eventdn and not 'extpaths' in eventdn: 89 | # leaf = re.search(r'protpaths-[0-9]{3}-[0-9]{3}', eventdn).group() 90 | # leaf = leaf.replace('protpaths', 'VPC node') 91 | # interface = re.search(r'pathep-.*\]', eventdn).group() 92 | # interface = interface.replace('pathep-', "") 93 | # portinterfaces = '{} {}'.format(leaf,interface[:-1]) 94 | #elif 'rsoosPath' in eventdn and 'extpaths' in eventdn: 95 | # leaf = re.search(r'paths-[0-9]{3}', eventdn).group() 96 | # leaf = leaf.replace('paths','node') 97 | # fex = re.search(r'extpaths-.*\]', eventdn).group() 98 | # interface = re.search(r'eth[0-9]{1,3}/[0-9]{1,3}', eventdn).group() 99 | # portinterfaces = '{} {} {}'.format(leaf,fex,interface) 100 | else: 101 | portinterfaces = "" 102 | diff_time = time_difference(eventcreated[:-6]) 103 | eventdict[num] = [eventcreated[:-6],eventtrig,eventuser,eventdn,eventdescr] 104 | print(('{:5}.) {:26}{:20}{:24}{}'.format(num,eventcreated[:-6],diff_time,portinterfaces,summaryeventdescr))) 105 | 106 | while True: 107 | moredetails = eval(input("\nMore details, select number [refresh=Blank and Enter]: ")) 108 | if moredetails == '': 109 | break 110 | if moredetails.isdigit() and eventdict.get(int(moredetails)): 111 | break 112 | else: 113 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 114 | if moredetails == '': 115 | continue 116 | diff_time = time_difference(eventdict[int(moredetails)][0]) 117 | print(('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','User','Object-Affected'))) 118 | print(('-'*120)) 119 | print(('{:26}{:20}{:18}{:18}{}\n'.format(eventdict[int(moredetails)][0],diff_time, eventdict[int(moredetails)][1],eventdict[int(moredetails)][2],'/'.join(str(eventdict[int(moredetails)][3]).split('/')[:-1])))) 120 | print('Event Details') 121 | print(('-'*15)) 122 | print((eventdict[int(moredetails)][4])) 123 | print('\n\n') 124 | refresh = askrefresh() 125 | if refresh == True: 126 | continue 127 | else: 128 | print('\nEnding Program...\n') 129 | break 130 | 131 | 132 | def main(): 133 | gatheranddisplayrecentevents() 134 | 135 | 136 | if __name__ == '__main__': 137 | try: 138 | main() 139 | except KeyboardInterrupt as k: 140 | print("\n\nExiting Program....") 141 | exit() 142 | -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/aci_health/most_recent_fault_changes.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib.request.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-Type", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def displaycurrenttime(): 31 | currenttime = datetime.datetime.now() 32 | return str(currenttime)[:-3] 33 | 34 | def time_difference(fault_time): 35 | currenttime = datetime.datetime.now() 36 | ref_fault_time = datetime.datetime.strptime(fault_time, '%Y-%m-%d %H:%M:%S.%f') 37 | return str(currenttime - ref_fault_time)[:-7] 38 | 39 | 40 | def askrefresh(): 41 | while True: 42 | refresh = eval(input("Return to fault list? [y=default|n]: ")) or 'y' 43 | if refresh[0].lower() == 'y': 44 | return True 45 | elif refresh[0].lower() == 'n': 46 | return False 47 | else: 48 | continue 49 | 50 | 51 | def gatheranddisplayrecentfaults(): 52 | while True: 53 | getCookie() 54 | os.system('clear') 55 | print(("Current time = " + displaycurrenttime())) 56 | url = """https://localhost/api/node/class/faultInfo.json?query-target-filter=and(ne(faultInfo.severity,"cleared"))&order-by=faultInfo.lastTransition|desc&page=0&page-size=100""" 57 | result, totalcount = GetResponseData(url) 58 | print(('\n{:>5} {:26}{:20}{:18}{:18}{}'.format('#','Time','Time Difference', 'Type','Fault-State','Fault Summary'))) 59 | print(('-'*175)) 60 | faultdict = {} 61 | for num,fault in enumerate(result,1): 62 | if fault.get('faultInst'): 63 | faultdescr = fault['faultInst']['attributes']['descr'].split() 64 | faultdescr = ' '.join(faultdescr) 65 | if len(faultdescr) > 120: 66 | summaryfaultdescr = faultdescr[:120] + '...' 67 | else: 68 | summaryfaultdescr = faultdescr 69 | faultlastTransition = ' '.join(fault['faultInst']['attributes']['lastTransition'].split('T')) 70 | faulttype = fault['faultInst']['attributes']['type'] 71 | faultstate = fault['faultInst']['attributes']['lc'] 72 | faultdn = fault['faultInst']['attributes']['dn'] 73 | diff_time = time_difference(faultlastTransition[:-6]) 74 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 75 | print(('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr))) 76 | else: 77 | faultdescr = fault['faultDelegate']['attributes']['descr'].split() 78 | faultdescr = ' '.join(faultdescr) 79 | if len(faultdescr) > 120: 80 | summaryfaultdescr = faultdescr[:120] + '...' 81 | else: 82 | summaryfaultdescr = faultdescr 83 | faultlastTransition = ' '.join(fault['faultDelegate']['attributes']['lastTransition'].split('T')) 84 | faulttype = fault['faultDelegate']['attributes']['type'] 85 | faultstate = fault['faultDelegate']['attributes']['lc'] 86 | faultdn = fault['faultDelegate']['attributes']['dn'] 87 | diff_time = time_difference(faultlastTransition[:-6]) 88 | faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 89 | print(('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr))) 90 | while True: 91 | moredetails = eval(input("\nMore details, select number [refresh=Blank and Enter]: ")) 92 | if moredetails == '': 93 | break 94 | if moredetails.isdigit() and faultdict.get(int(moredetails)): 95 | break 96 | else: 97 | print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 98 | if moredetails == '': 99 | continue 100 | diff_time = time_difference(faultdict[int(moredetails)][0]) 101 | print(('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','Fault-State','Object-Affected'))) 102 | print(('-'*120)) 103 | print(('{:26}{:20}{:18}{:18}{}\n'.format(faultdict[int(moredetails)][0],diff_time, faultdict[int(moredetails)][1],faultdict[int(moredetails)][2],'/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1])))) 104 | print('Fault Details') 105 | print(('-'*15)) 106 | print((faultdict[int(moredetails)][4])) 107 | print('\n\n') 108 | refresh = askrefresh() 109 | if refresh == True: 110 | continue 111 | else: 112 | print('\nEnding Program...\n') 113 | break 114 | 115 | 116 | def main(): 117 | gatheranddisplayrecentfaults() 118 | 119 | 120 | if __name__ == '__main__': 121 | try: 122 | main() 123 | except KeyboardInterrupt as k: 124 | print("\n\nExiting Program....") 125 | exit() 126 | -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/endpoint_history2.0.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | 10 | 11 | def GetRequest(url, icookie): 12 | method = "GET" 13 | cookies = 'APIC-cookie=' + icookie 14 | request = urllib.request.Request(url) 15 | request.add_header("cookie", cookies) 16 | request.add_header("Content-Type", "application/json") 17 | request.add_header('Accept', 'application/json') 18 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 19 | 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def validateipaddress(ip): 26 | result = re.search(r'^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$', ip) 27 | if result: 28 | return True 29 | return False 30 | 31 | def findipaddress(): 32 | ipaddr = eval(input("\nWhat is the ip address?: ")) 33 | # verify a valid ip format and its not a blank input 34 | if not validateipaddress(ipaddr) or ipaddr == '': 35 | return 36 | url = """https://localhost/api/node/class/fvCEp.json?rsp-subtree=full&rsp-subtree-include=required&rsp-subtree-filter=eq(fvIp.addr,"{}")""".format(ipaddr) 37 | result, totalcount = GetResponseData(url) 38 | try: 39 | # Check to see if there is no 'live' history of ip address 40 | if totalcount == '0': 41 | print('\n') 42 | print(("{:26}\t{:15}\t{:18}\t{}".format("Date", "encap-vlan", "Ip Address", "Mac Address"))) 43 | print(('-'*97)) 44 | # \x1b[41;1m is a special sequece to start red color for ansii color in terminal and \x1b[0m returns colors to normal 45 | print('\x1b[41;1mNo "LIVE Endpoint" IP found...check event history\x1b[0m\n') 46 | print('\n') 47 | # If 'live' history found, print history 48 | else: 49 | mac = result[0]['fvCEp']['attributes']['mac'] 50 | #encap = result[0]['fvCEp']['attributes']['encap'] 51 | dn = result[0]['fvCEp']['attributes']['dn'] 52 | # split 'dn' into a list and only keep uni->epg 53 | dnpath = '/'.join(dn.split('/')[:4]) 54 | print('\n') 55 | print(("{:26}\t{:15}\t{:18}\t{:20}\t{}".format("Date", "encap-vlan", "Ip Address", "Mac Address", "Path"))) 56 | print(('-'*115)) 57 | #url2 = """https://localhost/api/node/mo/uni/tn-SI/ap-APP-ISE/epg-EPG-VL10-ISE/cep-{}.json?query-target=subtree&target-subtree-class=fvCEp,fvRsCEpToPathEp,fvRsHyper,fvRsToNic,fvRsToVm""".format(mac) 58 | url3 = """https://localhost/mqapi2/troubleshoot.eptracker.json?ep={}/cep-{}&order-by=troubleshootEpTransition.date|desc&page=0&page-size=25""".format(dnpath,mac) 59 | 60 | result3, totalcount3 = GetResponseData(url3) 61 | for entry in result3: 62 | mac = entry['troubleshootEpTransition']['attributes']['mac'] 63 | ip = entry['troubleshootEpTransition']['attributes']['ip'] 64 | date = entry['troubleshootEpTransition']['attributes']['date'][:-6] 65 | encap_vlan = entry['troubleshootEpTransition']['attributes']['encap'] 66 | path = entry['troubleshootEpTransition']['attributes']['path'] 67 | 68 | leaf = re.search(r'paths-[0-9]{3}',path) 69 | if leaf: 70 | leaf = leaf.group().replace('paths-', '') 71 | interface = re.search(r'\[.*\]',path) 72 | if interface: 73 | interface = interface.group()[1:-1] 74 | fex = re.search(r'extpaths-[0-9]{3}',path) 75 | if fex: 76 | fex = fex.group().replace('extpaths-', '') 77 | path = 'leaf{} fex={} {}'.format(leaf,fex,interface) 78 | else: 79 | path = 'leaf{} {}'.format(leaf,interface) 80 | 81 | print(("{:26}\t{:15}\t{:18}\t{:20}\t{}".format(date, encap_vlan, ip, mac, path) )) 82 | except Exception as e: 83 | print(e) 84 | return 85 | history = eval(input("\nWould you like to see event history of {}? [y/n]: ".format(ipaddr))) 86 | if history != '' and history.lower() == 'y': 87 | return ipaddr 88 | else: 89 | return 0 90 | 91 | def searcheventrecords(ipaddr): 92 | #event record code E4209236 is "ip detached event" 93 | url = """https://localhost/api/node/class/eventRecord.json?query-target-filter=and(eq(eventRecord.code,"E4209236"))&""" \ 94 | """query-target-filter=and(wcard(eventRecord.descr,"{ipaddr}$"))&order-by=eventRecord.created|desc&page=0&page-size=25""".format(ipaddr=ipaddr) 95 | result, totalcount = GetResponseData(url) 96 | print('\n') 97 | if totalcount == '0': 98 | print(("{:.<45}0\n".format("Searching Event Records"))) 99 | else: 100 | print(("{:.<45}Found {} Events\n".format("Searching Event Records",totalcount))) 101 | 102 | print(("{:26}{:12}".format('Date','Description', ))) 103 | print(('-'*90)) 104 | if totalcount == '0': 105 | print(("\x1b[41;1mNo event history found for IP {}\x1b[0m\n\n".format(ipaddr))) 106 | return 107 | for event in result: 108 | timestamp = event['eventRecord']['attributes']['created'] 109 | descr = event['eventRecord']['attributes']['descr'] 110 | dn = event['eventRecord']['attributes']['dn'] 111 | mac = re.search(r'cep-.{17}', dn) 112 | print(("{:26}{:^12} [{}]".format(timestamp[:-6],descr,'mac: ' + mac.group()[4:]))) 113 | 114 | 115 | def main(): 116 | while True: 117 | os.system('clear') 118 | ipaddr = findipaddress() 119 | # If user desides not to search events but wants to look up another ip address 120 | if ipaddr == 0: 121 | ask = eval(input("\nCheck another ip address? [y/n]: ")) 122 | # if 'y' then restart the while loop to findipaddress() 123 | if ask.lower() == 'y' and ask != '': 124 | continue 125 | else: 126 | exit() 127 | # If user did want to search events and then look up another ip address afterwards 128 | elif ipaddr: 129 | searcheventrecords(ipaddr) 130 | ask = eval(input("\nCheck another ip address? [y/n]: ")) 131 | # if 'y' then restart the while loop to findipaddress() 132 | if ask.lower() == 'y' and ask != '': 133 | continue 134 | else: 135 | exit() 136 | 137 | if __name__ == '__main__': 138 | 139 | with open('/.aci/.sessions/.token', 'r') as f: 140 | cookie = f.read() 141 | 142 | main() 143 | -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/enpoint_gather_compare.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | import ipaddress 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib.request.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-trig", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def get_Cookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | class fvCEP(): 31 | def __init__(self, mac=None, ifId=None, name=None, 32 | pcTag=None, dn=None, flags=None): 33 | self.mac = mac 34 | self.ifId = ifId 35 | self.name = name 36 | self.pcTag = pcTag 37 | self.dn = dn 38 | self.flags = flags 39 | def __repr__(self): 40 | return self.dn 41 | def __getitem__(self, mac): 42 | if mac in self.mac: 43 | return self.mac 44 | else: 45 | return None 46 | 47 | class endpointip(): 48 | def __init__(self, forceResolve=None, ifId=None, name=None, 49 | pcTag=None, dn=None, flags=None): 50 | self.addr = addr 51 | self.ifId = ifId 52 | self.name = name 53 | self.pcTag = pcTag 54 | self.dn = dn 55 | self.flags = flags 56 | def __repr__(self): 57 | return self.dn 58 | def __getitem__(self, addr): 59 | if addr in self.addr: 60 | return self.addr 61 | else: 62 | return None 63 | 64 | get_Cookie() 65 | url = """https://localhost/api/class/epmMacEp.json""" 66 | result, totalamount = GetResponseData(url) 67 | epmMacEPlist = [x['epmMacEp']['attributes']['addr'] for x in result] 68 | print((len(epmMacEPlist))) 69 | set1 = set(epmMacEPlist) 70 | print((len(set1))) 71 | 72 | 73 | print('\n\n') 74 | url = """https://localhost/api/class/fvCEp.json""" 75 | result, totalamount = GetResponseData(url) 76 | fvCEplist = [x['fvCEp']['attributes']['mac'] for x in result] 77 | print((len(fvCEplist))) 78 | set2 = set(fvCEplist) 79 | print((len(set2))) 80 | 81 | print((set2-set1)) 82 | 83 | 84 | #https://192.168.255.2/api/class/epmMacEp.json?rsp-subtree=full 85 | # leaf directly https://192.168.255.101/api/class/epmMacEp.json?rsp-subtree=full -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/geolocationswitches.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | 11 | 12 | def GetRequest(url, icookie): 13 | method = "GET" 14 | cookies = 'APIC-cookie=' + icookie 15 | request = urllib.request.Request(url) 16 | request.add_header("cookie", cookies) 17 | request.add_header("Content-Type", "application/json") 18 | request.add_header('Accept', 'application/json') 19 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 20 | def GetResponseData(url): 21 | response = GetRequest(url, cookie) 22 | result = json.loads(response.read()) 23 | return result['imdata'], result["totalCount"] 24 | 25 | def getCookie(): 26 | global cookie 27 | with open('/.aci/.sessions/.token', 'r') as f: 28 | cookie = f.read() 29 | 30 | def main(): 31 | url = 'https://localhost/api/node/class/geoRsNodeLocation.json' 32 | result, totalCount = GetResponseData(url) 33 | print(result) 34 | 35 | if __name__ == '__main__': 36 | main() -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/gether_allendpoints_to_interface.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import ipaddress 9 | 10 | 11 | def GetRequest(url, icookie): 12 | method = "GET" 13 | cookies = 'APIC-cookie=' + icookie 14 | request = urllib.request.Request(url) 15 | request.add_header("cookie", cookies) 16 | request.add_header("Content-Type", "application/json") 17 | request.add_header('Accept', 'application/json') 18 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 19 | def GetResponseData(url): 20 | response = GetRequest(url, cookie) 21 | result = json.loads(response.read()) 22 | return result['imdata'], result["totalCount"] 23 | 24 | class fvCEp(): 25 | def __init__(self, mac=None, name=None, encap=None, 26 | lcC=None, dn=None, fvRsVm=None, fvRsHyper=None, 27 | fvRsCEpToPathEp=None, ip=None, fvIplist=[]): 28 | self.mac = mac 29 | self.name = name 30 | self.encap = encap 31 | self.dn = dn 32 | self.lcC = lcC 33 | self.fvRsVm = fvRsVm 34 | self.fvRsHyper = fvRsHyper 35 | self.ip = ip 36 | #self.iplist = iplist 37 | self.fvIplist = fvIplist 38 | self.fvRsCEpToPathEp = fvRsCEpToPathEp 39 | def __repr__(self): 40 | return self.dn 41 | def __getitem__(self, mac): 42 | if mac in self.mac: 43 | return self.mac 44 | else: 45 | return None 46 | def showips(self): 47 | iplist = [fvIP.addr for fvIP in self.fvIplist] 48 | return ', '.join(iplist) 49 | 50 | 51 | class fvIp(): 52 | def __init__(self, addr=None, rn=None,fvReportingNodes=None): 53 | self.addr = addr 54 | self.rn = rn 55 | self.fvReportingNodes = fvReportingNodes 56 | def __repr__(self): 57 | return self.addr 58 | def __getitem__(self, addr): 59 | if addr in self.addr: 60 | return self.addr 61 | else: 62 | return None 63 | 64 | class fvRsCEpToPathEp(): 65 | def __init__(self, tDn=None, lcC=None, fvReportingNodes=[], forceResolve=None): 66 | self.lcC = lcC #shows location it learned if 'vmm' vmm knows it cause vmware, 'vmm,learned' means vmware and switch knows, if just 'learned' not vmm source 67 | self.tDn = tDn # location of learned interface "topology/pod-1/paths-102/extpaths-112/pathep-[eth1/25]" example 68 | self.fvReportingNodes = fvReportingNodes # looks like port-channels use fvReportingNode api class (describes leafs where ep is discovered) 69 | self.forceResolve = forceResolve 70 | def __repr__(self): 71 | return self.tDn 72 | 73 | class fvRsVm(): 74 | def __init__(self, state=None, tDn=None, dn=None): 75 | self.state = state 76 | self.dn = dn 77 | self.tDn = tDn #internal vm name to lookup vmware vm name 78 | def __repr__(self): 79 | return self.tDn 80 | 81 | class fvRsHyper(): 82 | def __init__(self, state=None, tDn=None): 83 | self.state = state 84 | self.tDn = tDn #hyperviser internal name to look up vmware host name 85 | def __repr__(self): 86 | return self.tDn 87 | 88 | def get_Cookie(): 89 | global cookie 90 | with open('/.aci/.sessions/.token', 'r') as f: 91 | cookie = f.read() 92 | 93 | 94 | def gather_fvCEp_fullinfo(result): 95 | eplist = [] 96 | fvRsVmobject = None 97 | fvRsCEpToPathEpobject = None 98 | fvRsHyperobject = None 99 | fvIplist = [] 100 | for ep in result: 101 | fvReportingNodes = [] 102 | mac = ep['fvCEp']['attributes']['mac'] 103 | name = ep['fvCEp']['attributes']['name'] 104 | encap = ep['fvCEp']['attributes']['encap'] 105 | lcC = ep['fvCEp']['attributes']['lcC'] 106 | dn = ep['fvCEp']['attributes']['dn'] 107 | ip = ep['fvCEp']['attributes']['ip'] 108 | if ep['fvCEp'].get('children'): 109 | for ceptopath in ep['fvCEp']['children']: 110 | if ceptopath.get('fvRsCEpToPathEp') and ceptopath['fvRsCEpToPathEp']['attributes']['state'] == 'formed': 111 | fvRsCEpToPathEp_tDn = ceptopath['fvRsCEpToPathEp']['attributes']['tDn'] 112 | fvRsCEpToPathEp_lcC = ceptopath['fvRsCEpToPathEp']['attributes']['lcC'] 113 | fvRsCEpToPathEp_forceResolve = ceptopath['fvRsCEpToPathEp']['attributes']['forceResolve'] 114 | fvRsCEpToPathEpobject = fvRsCEpToPathEp(forceResolve=fvRsCEpToPathEp_forceResolve, 115 | tDn=fvRsCEpToPathEp_tDn, lcC=fvRsCEpToPathEp_lcC) 116 | elif ceptopath.get('fvIp'): 117 | fvIp_addr = ceptopath['fvIp']['attributes']['addr'] 118 | fvIp_rn = ceptopath['fvIp']['attributes']['rn'] 119 | if ceptopath['fvIp'].get('children'): 120 | fvReportingNodes = [node['fvReportingNode']['attributes']['rn'] for node in ceptopath['fvIp']['children']] 121 | else: 122 | fvReportingNodes = None 123 | fvIplist.append(fvIp(addr=fvIp_addr, rn=fvIp_rn, 124 | fvReportingNodes=fvReportingNodes)) 125 | elif ceptopath.get('fvRsVm') and ceptopath['fvRsVm']['attributes']['state'] == 'formed': 126 | fvRsVm_state = ceptopath['fvRsVm']['attributes']['state'] 127 | fvRsVm_tDn = ceptopath['fvRsVm']['attributes']['tDn'] 128 | fvRsVmobject = fvRsVm(state=fvRsVm_state, 129 | tDn=fvRsVm_tDn) 130 | elif ceptopath.get('fvRsHyper') and ceptopath['fvRsHyper']['attributes']['state'] == 'formed': 131 | fvRsHyper_state = ceptopath['fvRsHyper']['attributes']['state'] 132 | fvRsHyper_tDn = ceptopath['fvRsHyper']['attributes']['tDn'] 133 | fvRsHyperobject = fvRsHyper(state=fvRsHyper_state, 134 | tDn=fvRsHyper_tDn) 135 | eplist.append(fvCEp(mac=mac, name=name, encap=encap, 136 | lcC=lcC, dn=dn, fvRsVm=fvRsVmobject, fvRsCEpToPathEp=fvRsCEpToPathEpobject, 137 | ip=ip, fvRsHyper=fvRsHyperobject, fvIplist=fvIplist)) 138 | fvIplist = [] 139 | return eplist 140 | 141 | 142 | def mac_path_function(): 143 | url = """https://localhost/api/node/class/fvCEp.json?rsp-subtree=full&target-subtree-class=fvCEp,fvRsCEpToPathEp""" 144 | result, totalcount = GetResponseData(url) 145 | fvCEplist = gather_fvCEp_fullinfo(result) 146 | #print(fvCEplist) 147 | for x in fvCEplist: 148 | #print("{:25}{:20}{:20}{}".format(x.mac, x.ip, x.fvIplist, x.fvRsCEpToPathEp)) 149 | print(("{},{},{},{}".format(x.mac,x.ip,x.fvIplist,x.fvRsCEpToPathEp))) 150 | print(totalcount) 151 | #for fvCEp in fvCEplist: 152 | # result, totalcount = GetResponseData(url) 153 | # completefvCEplist = gather_fvCEp_fullinfo(result) 154 | # #print(completefvCEplist) 155 | # #Display current endpoint info 156 | # 157 | # find_current_ep_info(completefvCEplist[0], totalcount) 158 | # #Display current known endpoint history 159 | # display_live_history_info(completefvCEplist[0], totalcount) 160 | 161 | 162 | def main(): 163 | get_Cookie() 164 | mac_path_function() 165 | 166 | if __name__ == '__main__': 167 | main() 168 | -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/health_reasons.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import ipaddress 9 | 10 | 11 | ipaddr = None 12 | 13 | def GetRequest(url, icookie): 14 | method = "GET" 15 | cookies = 'APIC-cookie=' + icookie 16 | request = urllib.request.Request(url) 17 | request.add_header("cookie", cookies) 18 | request.add_header("Content-Type", "application/json") 19 | request.add_header('Accept', 'application/json') 20 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 21 | def GetResponseData(url): 22 | response = GetRequest(url, cookie) 23 | result = json.loads(response.read()) 24 | return result['imdata'], result["totalCount"] 25 | 26 | def get_Cookie(): 27 | global cookie 28 | with open('/.aci/.sessions/.token', 'r') as f: 29 | cookie = f.read() 30 | get_Cookie() 31 | #url = """https://localhost/api/node/mo/topology/pod-1/node-101/sys.json?query-target=children&rsp-subtree-include=health,fault-count""" 32 | #result, totalcount = GetResponseData(url) 33 | #for object in result: 34 | # for currentobject in object: 35 | # print(currentobject) 36 | # if object[currentobject]['children']: 37 | # for ob in object[currentobject]['children']: 38 | # if ob.get('healthInst'): 39 | # print(ob['healthInst']) 40 | 41 | 42 | #url = """https://localhost/api/node/mo/topology/pod-1/node-102/sys/ch.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""" 43 | #result, totalcount = GetResponseData(url) 44 | #for object in result: 45 | # for currentobject in object: 46 | # print(currentobject, object[currentobject]['children'][0]['healthInst']['attributes']['cur']) 47 | 48 | url = """https://localhost/api/node/mo/topology/pod-1/node-102/sys.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""" 49 | result, totalcount = GetResponseData(url) 50 | for object in result: 51 | for currentobject in object: 52 | #print(currentobject, object[currentobject]['children'][0]['healthInst']['attributes']['cur'], object[currentobject]['attributes']['dn']) 53 | url = """https://localhost/api/node/mo/{}.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""".format(object[currentobject]['attributes']['dn']) 54 | #print(url) 55 | result2, totalcount = GetResponseData(url) 56 | for object2 in result2: 57 | for currentobject2 in object2: 58 | #pass 59 | #print(currentobject2, object2[currentobject2]['children'][0]['healthInst']['attributes']['cur'], object2[currentobject2]['attributes']['dn']) 60 | url = """https://localhost/api/node/mo/{}.json?query-target=children&rsp-subtree-include=health,required&rsp-subtree-filter=lt(healthInst.cur,"100")""".format(object2[currentobject2]['attributes']['dn']) 61 | result3, totalcount = GetResponseData(url) 62 | for object3 in result3: 63 | for currentobject3 in object3: 64 | print((currentobject3, object3[currentobject3]['children'][0]['healthInst']['attributes']['cur'], object3[currentobject3]['attributes']['dn'])) 65 | #url = """https://localhost/api/node/class/faultInst.json?query-target-filter=eq(wcard(faultInst,"102"))""" 66 | #result, totalcount = GetResponseData(url) 67 | #print(result) -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/healthistory.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | import datetime 10 | import itertools 11 | import trace 12 | import pdb 13 | import datetime 14 | 15 | def GetRequest(url, icookie): 16 | method = "GET" 17 | cookies = 'APIC-cookie=' + icookie 18 | request = urllib.request.Request(url) 19 | request.add_header("cookie", cookies) 20 | request.add_header("Content-type", "application/json") 21 | request.add_header('Accept', 'application/json') 22 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 23 | def GetResponseData(url): 24 | response = GetRequest(url, cookie) 25 | result = json.loads(response.read()) 26 | return result['imdata'], result["totalCount"] 27 | 28 | 29 | 30 | class healthscores(): 31 | def __init__(self, **kwargs): 32 | self.__dict__.update(kwargs) 33 | def __repr__(self): 34 | return self.healthMin 35 | 36 | 37 | def grouper(iterable, n, fillvalue=''): 38 | "Collect data into fixed-length chunks or blocks" 39 | # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" 40 | args = [iter(iterable)] * n # creates list * n so args is a list of iters for iterable 41 | return itertools.zip_longest(*args, fillvalue=fillvalue) 42 | 43 | def get_Cookie(): 44 | global cookie 45 | with open('/.aci/.sessions/.token', 'r') as f: 46 | cookie = f.read() 47 | get_Cookie() 48 | url = """https://localhost/api/node/mo/topology.json?rsp-subtree-include=stats&rsp-subtree-class=fabricOverallHealthHist5min""" 49 | result, totalcount = GetResponseData(url) 50 | 51 | healthlist = [] 52 | for health in result[0]['fabricTopology']['children']: 53 | #print(health) 54 | healthlist.append(healthscores(**health['fabricOverallHealthHist5min']['attributes'])) 55 | healthlist = sorted(healthlist, key=lambda x: x.repIntvEnd) 56 | grouped = grouper(healthlist, 96) 57 | 58 | print(grouped) 59 | healthlist = list(zip(*grouped)) 60 | for h in healthlist: 61 | print(h) 62 | #if h.healthMin < h.healthAvg: 63 | # aa = 31 64 | #else: 65 | # aa = 37 66 | #if h.healthMax > h.healthAvg: 67 | # cc = 32 68 | #else: 69 | # cc = 37 70 | #print('\x1b[1;{};40m{}\x1b[0m {} \x1b[1;{};40m{}\x1b[0m {}'.format(aa,h.healthMin,h.healthAvg,cc,h.healthMax, h.repIntvEnd)) 71 | #zip(h.healthMin, h.healthMax, h.healthAvg) 72 | 73 | 74 | #for a,b,c in kk: 75 | # if a < b: 76 | # aa = 31 77 | # else: 78 | # aa = 37 79 | # if c > b: 80 | # cc = 32 81 | # else: 82 | # cc = 37 83 | # print('\x1b[1;{};40m{}\x1b[0m {} \x1b[1;{};40m{}\x1b[0m'.format(aa,a,b,cc,c)) -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/interface_information/interface-egps.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | 3 | #import re 4 | import readline 5 | import urllib.request, urllib.error, urllib.parse 6 | import json 7 | import ssl 8 | import os 9 | 10 | def GetRequest(url, icookie): 11 | method = "GET" 12 | cookies = 'APIC-cookie=' + icookie 13 | request = urllib.request.Request(url) 14 | request.add_header("cookie", cookies) 15 | request.add_header("Content-Type", "application/json") 16 | request.add_header('Accept', 'application/json') 17 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 18 | def GetResponseData(url): 19 | response = GetRequest(url, cookie) 20 | result = json.loads(response.read()) 21 | return result['imdata'], result["totalCount"] 22 | 23 | def retrieve_leaf_list(): 24 | # Display available leafs beginning of script 25 | url = """https://localhost/api/node/mo/topology/pod-1.json?query-target=children&target-subtree-class=fabricNode&query-target-filter=and(wcard(fabricNode.id,"^1[0-9][0-9]"))""" 26 | result, totalcount = GetResponseData(url) 27 | #print(result) 28 | leafs = [leaf['fabricNode']['attributes']['id'] for leaf in result] 29 | #print('Available leafs to bounce ports...') 30 | return leafs 31 | 32 | def displayepgs(result): 33 | print(('\n{:10}{:15}{}'.format('Tenant','APP','EPG'))) 34 | print(('-'*40)) 35 | #print(result) 36 | if result[0]['l1PhysIf']['attributes']['layer'] == 'Layer3': 37 | print('Layer 3 interface, no EPGs\n') 38 | return 39 | if result[0]['l1PhysIf'].get('children'): 40 | for int in result[0]['l1PhysIf']['children']: 41 | for epgs in int['pconsCtrlrDeployCtx']['children']: 42 | epgpath = epgs['pconsResourceCtx']['attributes']['ctxDn'].split('/') 43 | #print(epgpath) 44 | tenant = epgpath[1][3:] 45 | app = epgpath[2][3:] 46 | epg = epgpath[3][4:] 47 | print(('{:10}{:15}{}'.format(tenant,app,epg))) 48 | print('\n') 49 | else: 50 | print('No Epgs found...\n') 51 | 52 | 53 | with open('/.aci/.sessions/.token', 'r') as f: 54 | cookie = f.read() 55 | 56 | def gatherandstoreinterfacesforleaf(leaf): 57 | url = """https://localhost/api/node/class/topology/pod-1/node-101/l1PhysIf.json""" 58 | result, totalcount = GetResponseData(url) 59 | listofinterfaces = [interface['l1PhysIf']['attributes']['id'] for interface in result] 60 | return listofinterfaces 61 | 62 | def main(): 63 | fex = False 64 | print(("\n1.) Physical interface\n" + 65 | "2.) Port-channel/vPC\n")) 66 | int_type = eval(input("What is the interface type?: ")) 67 | if int_type == '1': 68 | listleafs = retrieve_leaf_list() 69 | print(('\nAvailable Leafs\n' + '-'*12)) 70 | for leaf in sorted(listleafs): 71 | print(leaf)#Leaf' + ' Leaf'.join(leafs)) 72 | print('\r') 73 | while True: 74 | leaf = eval(input("What is leaf number?: ")) 75 | if leaf in listleafs: 76 | break 77 | else: 78 | print('\x1b[41;1mInvalid or leaf does not exist...try again\x1b[0m\n') 79 | availableinterfaces = gatherandstoreinterfacesforleaf(leaf) 80 | #while True: 81 | # askfex = raw_input("Fex interface? [y|n] (default=n): ") or 'n' 82 | # if askfex[0].lower() == 'y': 83 | # fex = True 84 | # break 85 | # else: 86 | # break 87 | while True: 88 | if fex == True: 89 | interface = eval(input("What is the interface? (format: ethxxx/x/x): ")) 90 | else: 91 | interface = eval(input("What is the interface? (format: ethx/x): ")) 92 | if interface in availableinterfaces: 93 | break 94 | else: 95 | print('\x1b[41;1mInvalid or interface does not exist...try again\x1b[0m\n') 96 | 97 | url = """https://localhost/api/node/mo/topology/pod-1/node-{leaf}/sys/phys-[{interface}].json?rsp-subtree-include=full-deployment&target-node=all&target-path=l1EthIfToEPg""".format(leaf=leaf,interface=interface) 98 | #print(url) 99 | result, totalcount = GetResponseData(url) 100 | displayepgs(result) 101 | elif int_type == 2: 102 | pass 103 | else: 104 | pass 105 | 106 | 107 | 108 | if __name__ == '__main__': 109 | while True: 110 | main() 111 | ask = eval(input('Another interface? [y|n]: ')) or 'n' 112 | #print(ask) 113 | if ask[0].lower() == 'y': 114 | continue 115 | else: 116 | break 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/routing.py: -------------------------------------------------------------------------------- 1 | import re 2 | import readline 3 | import urllib.request, urllib.error, urllib.parse 4 | import json 5 | import ssl 6 | import os 7 | import datetime 8 | 9 | def displaycurrenttime(): 10 | currenttime = datetime.datetime.now() 11 | return str(currenttime)[:-3] 12 | 13 | def time_difference(fault_time): 14 | currenttime = datetime.datetime.now() 15 | ref_fault_time = datetime.datetime.strptime(fault_time, '%Y-%m-%d %H:%M:%S.%f') 16 | return str(currenttime - ref_fault_time)[:-7] 17 | 18 | 19 | def GetRequest(url, icookie): 20 | method = "GET" 21 | cookies = 'APIC-cookie=' + icookie 22 | request = urllib.request.Request(url) 23 | request.add_header("cookie", cookies) 24 | request.add_header("Content-Type", "application/json") 25 | request.add_header('Accept', 'application/json') 26 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 27 | def GetResponseData(url): 28 | response = GetRequest(url, cookie) 29 | result = json.loads(response.read()) 30 | return result['imdata'], result["totalCount"] 31 | 32 | def getCookie(): 33 | global cookie 34 | with open('/.aci/.sessions/.token', 'r') as f: 35 | cookie = f.read() 36 | 37 | 38 | def askrefresh(): 39 | while True: 40 | refresh = eval(input("Return to fault list? [y=default|n]: ")) or 'y' 41 | if refresh[0].lower() == 'y': 42 | return True 43 | elif refresh[0].lower() == 'n': 44 | return False 45 | else: 46 | continue 47 | 48 | 49 | def gatheranddisplayrecentfaults(): 50 | while True: 51 | getCookie() 52 | os.system('clear') 53 | print(("Current time = " + displaycurrenttime())) 54 | url = """https://localhost/api/node/class/uribv4Route.json?rsp-subtree=full""" 55 | #result, totalcount = GetResponseData(url) 56 | #url2 ="""https://localhost/api/node/mo/topology/pod-1/node-101/sys/uribv4/dom-SI:SI/db-rt/rt-[0.0.0.0/0].json?query-target=children&target-subtree-class=uribv4Nexthop&query-target-filter=not(wcard(uribv4Nexthop.dn,%22__ui_%22))""" 57 | #print(result) 58 | #print(result) 59 | result, totalcount = GetResponseData(url) 60 | print('done') 61 | #print(result) 62 | break 63 | 64 | # faultdict = {} 65 | # for num,fault in enumerate(result,1): 66 | # if fault.get('faultInst'): 67 | # faultdescr = fault['faultInst']['attributes']['descr'].split() 68 | # faultdescr = ' '.join(faultdescr) 69 | # if len(faultdescr) > 120: 70 | # summaryfaultdescr = faultdescr[:120] + '...' 71 | # else: 72 | # summaryfaultdescr = faultdescr 73 | # faultlastTransition = ' '.join(fault['faultInst']['attributes']['lastTransition'].split('T')) 74 | # faulttype = fault['faultInst']['attributes']['type'] 75 | # faultstate = fault['faultInst']['attributes']['lc'] 76 | # faultdn = fault['faultInst']['attributes']['dn'] 77 | # #print(faultlastTransition) 78 | # diff_time = time_difference(faultlastTransition[:-6]) 79 | # faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 80 | # print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 81 | # else: 82 | # faultdescr = fault['faultDelegate']['attributes']['descr'].split() 83 | # faultdescr = ' '.join(faultdescr) 84 | # if len(faultdescr) > 120: 85 | # summaryfaultdescr = faultdescr[:120] + '...' 86 | # else: 87 | # summaryfaultdescr = faultdescr 88 | # faultlastTransition = ' '.join(fault['faultDelegate']['attributes']['lastTransition'].split('T')) 89 | # faulttype = fault['faultDelegate']['attributes']['type'] 90 | # faultstate = fault['faultDelegate']['attributes']['lc'] 91 | # faultdn = fault['faultDelegate']['attributes']['dn'] 92 | # diff_time = time_difference(faultlastTransition[:-6]) 93 | # faultdict[num] = [faultlastTransition[:-6],faulttype,faultstate,faultdn,faultdescr] 94 | # print('{:5}.) {:26}{:20}{:18}{:18}{}'.format(num,faultlastTransition[:-6],diff_time,faulttype,faultstate,summaryfaultdescr)) 95 | # 96 | # 97 | # while True: 98 | # moredetails = raw_input("\nMore details, select number: ") 99 | # if moredetails.isdigit() and faultdict.get(int(moredetails)): 100 | # break 101 | # else: 102 | # print('\x1b[41;1mInvalid, number does not exist...try again\x1b[0m\n') 103 | # diff_time = time_difference(faultdict[int(moredetails)][0]) 104 | # print('\n\n{:26}{:20}{:18}{:18}{}'.format('Time','Time Difference', 'Type','Fault-State','Object-Affected')) 105 | # print('-'*120) 106 | # #print('/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1])) 107 | # print('{:26}{:20}{:18}{:18}{}\n'.format(faultdict[int(moredetails)][0],diff_time, faultdict[int(moredetails)][1],faultdict[int(moredetails)][2],'/'.join(str(faultdict[int(moredetails)][3]).split('/')[:-1]))) 108 | # print('Fault Details') 109 | # print('-'*15) 110 | # print(faultdict[int(moredetails)][4]) 111 | # print('\n\n') 112 | # 113 | # refresh = askrefresh() 114 | # if refresh == True: 115 | # continue 116 | # else: 117 | # print('\nEnding Program...\n') 118 | # break 119 | 120 | 121 | def main(): 122 | gatheranddisplayrecentfaults() 123 | 124 | 125 | if __name__ == '__main__': 126 | main() -------------------------------------------------------------------------------- /python3_migration/misc_unfinished_scripts/urlib.py: -------------------------------------------------------------------------------- 1 | #!/bin//python 2 | import readline 3 | import urllib.request, urllib.error, urllib.parse 4 | import json 5 | import base64 6 | import ssl 7 | import getpass 8 | import os 9 | 10 | os.system('clear') 11 | 12 | username = eval(input('username: ')) 13 | password = getpass.getpass('(Backspace not supported...blame APIC terminal)\npassword: ') 14 | print(password) 15 | 16 | def addingmultipleheaders(items,request): 17 | if type(items) == list: 18 | for x, y in items: 19 | request.add_header(x,y) 20 | 21 | def GetRequest(url): 22 | method = "GET" 23 | request = urllib.request.Request(url) 24 | request.add_header("Content-Type", "application/json") 25 | request.add_header('Accept', 'application/json') 26 | #addingmultipleheaders([("Content-Type", "application/json"),('Accept', 'application/json')], request) 27 | base64string = base64.b64encode('%s:%s' % (str(username), str(password))) 28 | request.add_header("Authorization", "Basic %s" % base64string) 29 | return urllib.request.urlopen(request, context=ssl._create_unverified_context()) 30 | 31 | 32 | url = 'https://10.100.100.29:9060/ers/config/endpoint' #.format(endpointmac) 33 | response = GetRequest(url) 34 | 35 | print('\r') 36 | endpointmac = str(eval(input('Last 4 of MAC? : '))) 37 | print('\r') 38 | #convert any mac combination (. or :) to API acceptiable MAC format 39 | if '.' in endpointmac or ':' in endpointmac: 40 | endpointmac.replace('.', '').replace(':', '') 41 | endpointmac = ':'.join(endpointmac[i:i+2] for i in range(0, len(endpointmac), 2)) 42 | endpointmac = endpointmac.upper() 43 | 44 | # 45 | #url = 'https://10.100.100.29:9060/ers/config/endpoint' #.format(endpointmac) 46 | #response = GetRequest(url) 47 | if response: 48 | possiblematches = [] 49 | matchdic = {} 50 | getendpointresult = json.loads(response.read()) 51 | for idfound in getendpointresult['SearchResult']['resources']: 52 | if endpointmac in idfound['name']: 53 | possiblematches.append(idfound['name']) 54 | if possiblematches: 55 | #print('\n') 56 | print("Found Possible MACs:") 57 | #matchdic = {} 58 | #start = 0 59 | for num, mac in enumerate(possiblematches, 1): 60 | matchdic[num] = mac 61 | print(('\t' + str(num) + '.) ' + mac)) 62 | else: 63 | print('No matches found') 64 | # print('\n') 65 | # print('***********************') 66 | # print('Available Groups:') 67 | if len(possiblematches) == 1: 68 | endpointmac = possiblematches[0] 69 | elif len(possiblematches) > 1: 70 | print('\r') 71 | numberselected = int(eval(input('Select MAC address #: '))) 72 | endpointmac = matchdic[numberselected] 73 | else: 74 | print("No Matches found") 75 | print('\r') 76 | print('Available Groups:') 77 | print('***********************') 78 | 79 | url = 'https://10.100.100.29:9060/ers/config/endpoint/name/{}'.format(endpointmac) 80 | response = GetRequest(url) 81 | if response: 82 | getendpointresult = json.loads(response.read()) 83 | endpointid = getendpointresult['ERSEndPoint']['id'] 84 | 85 | 86 | url = 'https://10.100.100.29:9060/ers/config/endpointgroup' 87 | response = GetRequest(url) 88 | if response: 89 | #print(response.read()) 90 | groupdic = {} 91 | allgroupresult = json.loads(response.read()) 92 | listofgroups = allgroupresult['SearchResult']['resources'] 93 | for num, group in enumerate(listofgroups, 1): 94 | print(('\t' + str(num) + '.) ' + group['name'])) 95 | groupdic[num] = group['name'] 96 | 97 | 98 | print('\r') 99 | desiredgroup = int(eval(input('What is new Endpoint Group?: '))) 100 | #print(desiredgroup) 101 | #desiredgroup = str(groupdic[desiredgroup]) 102 | #print(desiredgroup) 103 | url = 'https://10.100.100.29:9060/ers/config/endpointgroup/name/{}'.format(groupdic[desiredgroup]) 104 | 105 | response = GetRequest(url) 106 | if response: 107 | endgroupresult = json.loads(response.read()) 108 | endpointgroupid = endgroupresult['EndPointGroup']['id'] 109 | 110 | 111 | 112 | url = "https://10.100.100.27:9060/ers/config/endpoint/{}".format(endpointid) 113 | data = json.dumps({"ERSEndPoint": {"groupId": endpointgroupid, "staticGroupAssignment": True}}) 114 | method = "PUT" 115 | request = urllib.request.Request(url, data) 116 | addingmultipleheaders([("Content-Type", "application/json"),('Accept', 'application/json')], request) 117 | base64string = base64.b64encode('%s:%s' % (str(username), str(password))) 118 | request.add_header("Authorization", "Basic %s" % base64string) 119 | request.get_method = lambda: method 120 | #if data: request.add_data(data) 121 | response = urllib.request.urlopen(request, context=ssl._create_unverified_context()) 122 | if response: 123 | responseoutput = response.read() 124 | if responseoutput == '{\n "UpdatedFieldsList" : {\n "updatedField" : [ ]\n }\n}': 125 | print(("""\n(INFO) MAC already using """ + groupdic[desiredgroup] + '\n')) 126 | else: 127 | if response.getcode() == 200: 128 | print(("\nSuccess: Endpoint updated to " + groupdic[desiredgroup] + "\n")) 129 | #print(response.getcode()) 130 | #print(responseoutput) 131 | -------------------------------------------------------------------------------- /python3_migration/shut_interfaces/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/settlej/ACI_Ops/558deb06ac1939a7dfc41c73244d9a334d753618/python3_migration/shut_interfaces/__init__.py --------------------------------------------------------------------------------