如何在Python中匹配字符串格式的指定端口范围并筛选Down状态端口
解决方案:筛选指定范围的Down状态端口
你只需要在原有的状态判断基础上,添加端口号的范围校验即可,注意要把字符串类型的端口号转成整数再比较(避免字符串排序的问题)。
修改后的完整代码
import netmiko from netmiko import ConnectHandler from getpass4 import getpass user = 'example_user' password = getpass('Password: ') net_connect = ConnectHandler( device_type="hp_procurve", host="10.0.0.1", username=user, password=password, ) print('*** Sending command ***') show_int_brief = net_connect.send_command("show int brief", use_textfsm=True) net_connect.disconnect() int_down = [] for item in show_int_brief: if item['status'] == 'Down': try: port_num = int(item['port']) # 匹配3-6或38-52的端口范围 if (3 <= port_num <= 6) or (38 <= port_num <= 52): int_down.append(item['port']) except ValueError: # 跳过非数字格式的端口(比如聚合口、特殊端口) continue print('*** Port status known as down ***\n', int_down)
关键说明
- 端口号类型转换:原数据中
port是字符串类型,直接用字符串比较会出问题(比如'10' < '3'会返回True),所以必须转成整数再做范围判断。 - 范围校验逻辑:用
(3 <= port_num <=6) or (38 <= port_num <=52)精准匹配你需要的两个端口区间。 - 容错处理:添加
try-except块是为了兼容交换机上可能存在的非数字端口(比如聚合端口A1、Trunk1这类),遇到这类端口直接跳过,避免脚本报错。
简洁版(列表推导式)
如果你的交换机端口都是纯数字格式,也可以用更简洁的列表推导式实现:
int_down = [ item['port'] for item in show_int_brief if item['status'] == 'Down' and (3 <= int(item['port']) <= 6 or 38 <= int(item['port']) <= 52) ]
内容的提问来源于stack exchange,提问作者BrodieFrankfurt
相关产品推荐
相关产品推荐

