使用requests.get调用RESTCONF批量获取端口数据返回404,curl可正常工作
问题原因与解决方法
问题根源
你遇到的404错误是因为shell的大括号展开机制:在shell中执行curl命令时,{1,2}会被shell自动展开为两个独立的请求路径——port=1和port=2,curl会依次请求这两个URL并合并输出结果。但Python的requests库不会处理这种shell层面的语法展开,它会直接将{1,2}作为URL的字面量发送给设备,而你的设备RESTCONF接口无法识别该格式,因此返回404错误。
解决方法
方法1:手动模拟shell的多请求合并
在Python中循环请求每个端口,再合并结果,和curl的行为保持一致:
import requests import json # 定义要请求的端口列表 target_ports = [1, 2] results = [] # 复用你的请求头和认证信息 request_header = self.header auth_info = (self.username1, self.password1) for port in target_ports: # 构造单个端口的请求URL single_port_url = f"https://IP/api/data/switch:opm/port={port}" response = requests.get(single_port_url, headers=request_header, auth=auth_info, verify=False) if response.status_code == 200: results.append(response.json()) # 合并结果,匹配curl的输出格式 combined_output = "\n".join(json.dumps(item) for item in results) print(combined_output)
方法2:尝试设备支持的批量参数格式
部分设备的RESTCONF接口支持用逗号分隔多个资源ID,你可以直接修改URL为逗号分隔形式:
url = "https://IP/api/data/switch:opm/port=1,2" response = requests.get(url, headers=self.header, auth=(self.username1, self.password1), verify=False)
如果设备支持该语法,就能一次性获取多个端口的数据。
方法3:对大括号进行URL编码(若设备需要原始语法)
如果设备确实要求{1,2}格式的参数,需要对URL中的特殊字符进行编码:
import requests from urllib.parse import quote # 对大括号参数进行URL编码 encoded_param = quote("{1,2}") # 构造编码后的URL url = f"https://IP/api/data/switch:opm/port={encoded_param}" response = requests.get(url, headers=self.header, auth=(self.username1, self.password1), verify=False)
编码后的URL会变为https://IP/api/data/switch:opm/port=%7B1%2C2%7D,可尝试是否被设备识别。
内容的提问来源于stack exchange,提问作者dem
相关产品推荐
相关产品推荐

