交换机自动化升级脚本TypeError问题求助:list indices must be integers or slices, not str
Fix for TypeError When Accessing
peer_state in Redundancy Check Code Let's break down why you're hitting that TypeError and fix it quickly:
The Root Cause
Your task.host['redundancy'] is a double-nested list structure:
[ [ {'redundancy': {...}} # This is the actual dict you care about ] ]
When you run for i in task.host['redundancy'], the first (and only) value of i is the inner list [{'redundancy': {...}}]—not a dictionary. Trying to index a list with a string like 'peer_state' will throw the error you're seeing.
Fixed Code for verify_redundancy
Here's the corrected function with proper structure parsing, better error handling, and clearer feedback:
from netmiko import Result from colorama import Style, Fore, Back def verify_redundancy(task): target_peer_state = 'ACTIVE' try: # Drill through the double-nested list to get the redundancy data dict redundancy_data = task.host['redundancy'][0][0]['redundancy'] current_peer_state = redundancy_data['peer_state'] if current_peer_state == target_peer_state: results = f"Redundancy check: Found expected peer state '{target_peer_state}'" check_status = 'Y' task.host['check'] = check_status return Result( host=task.host, result=f"{Style.BRIGHT} {Fore.WHITE}{Back.GREEN} {results}", check=check_status ) else: results = f"Redundancy check: Expected '{target_peer_state}', but found '{current_peer_state}'" check_status = 'N' task.host['check'] = check_status return Result( host=task.host, result=f"{Style.BRIGHT} {Fore.WHITE}{Back.RED} {results}", check=check_status ) except IndexError: # Handle cases where the nested list structure isn't as expected results = "Error: Redundancy data has unexpected nested list structure" check_status = 'N' task.host['check'] = check_status return Result( host=task.host, result=f"{Style.BRIGHT} {Fore.WHITE}{Back.YELLOW} {results}", check=check_status ) except KeyError as e: # Handle missing keys in the redundancy data results = f"Error: Missing expected key in redundancy data: {str(e)}" check_status = 'N' task.host['check'] = check_status return Result( host=task.host, result=f"{Style.BRIGHT} {Fore.WHITE}{Back.YELLOW} {results}", check=check_status )
Key Improvements
- Direct Structure Parsing: We use
task.host['redundancy'][0][0]['redundancy']to skip past the two nested lists and get straight to the dictionary containing your peer state data. - Robust Error Handling: Added
try/exceptblocks to catch cases where the data structure changes or keys go missing—this prevents your script from crashing unexpectedly. - Clearer Feedback: Updated success/failure messages to include the actual state found, and adjusted colors (red for failed state checks, yellow for structural errors) to make statuses easier to scan.
- Cleaner Variable Names: Renamed variables like
peer_statetotarget_peer_statefor better readability.
内容的提问来源于stack exchange,提问作者Michal Obsitnik
相关产品推荐
相关产品推荐

