Netmiko执行交换机查询时如何在命令中正确引用变量获取输出
问题原因
你第一种写法的问题在于:直接把变量名写在了单引号包裹的静态字符串中,Python不会自动解析字符串内部的变量名,因此实际发送给交换机的命令是show mac-address-table | inc mac_address,而非携带你定义的MAC值的命令,自然不会返回匹配结果。
解决方案
以下三种常用写法都可以实现变量的正确拼接,任选其一即可:
- 方法1:使用f-string拼接(Python 3.6及以上版本支持,写法最简洁)
mac_address = "abcd" # 字符串前加f,变量用{}包裹即可实现解析 output = net_connect.send_command(f'show mac-address-table | inc {mac_address}') print("Output of the switch ", output)
- 方法2:使用字符串加号拼接
mac_address = "abcd" cmd = 'show mac-address-table | inc ' + mac_address output = net_connect.send_command(cmd) print("Output of the switch ", output)
- 方法3:使用str.format()方法拼接
mac_address = "abcd" output = net_connect.send_command('show mac-address-table | inc {}'.format(mac_address)) print("Output of the switch ", output)
注意事项
如果实际使用的MAC地址带分隔符(比如aabb.ccdd.1122、aa:bb:cc:dd:ee:ff格式),变量赋值时要包裹引号,作为字符串类型处理,避免触发Python语法错误。
内容的提问来源于stack exchange,提问作者curious_21
相关产品推荐
相关产品推荐

