Curl命令转Python requests脚本报错求助:无法建立连接
Curl转Python requests脚本的问题修复
原Curl命令
export NEXRAN_XAPP=`sudo kubectl get svc -n ricxapp --field-selector metadata.name=service-ricxapp-nexran-rmr -o jsonpath='{.items[0].spec.clusterIP}'` curl -i -X PUT -H "Content-type: application/json" -d '{"allocation_policy":{"type":"proportional","share":1024}}' http://${NEXRAN_XAPP}:8000/v1/slices/slow curl -i -X PUT -H "Content-type: application/json" -d '{"allocation_policy":{"type":"proportional","share":256}}' http://${NEXRAN_XAPP}:8000/v1/slices/fast
错误的Python脚本
import requests import os os.system ("export NEXRAN_XAPP=`kubectl get svc -n ricxapp --field-selector metadata.name=service-ricxapp-nexran-rmr -o jsonpath='{.items[0].spec.clusterIP}'`") headers = { 'Content-type': 'application/json', } data1 = '{"allocation_policy":{"type":"proportional","share":1024}}' data2 = '{"allocation_policy":{"type":"proportional","share":256}}' response1 = requests.put('http://${NEXRAN_XAPP}:8000/v1/slices/fast', headers=headers, data=data1) response2 = requests.put('http://${NEXRAN_XAPP}:8000/v1/slices/slow', headers=headers, data=data2)
报错信息
Traceback (most recent call last): File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 159, in _new_conn conn = connection.create_connection( File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 61, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "/usr/lib/python3.8/socket.py", line 918, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 665, in urlopen httplib_response = self._make_request( File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 387, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3.8/http/client.py", line 1256, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1302, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1251, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.8/http/client.py", line 1011, in _send_output self.send(msg) File "/usr/lib/python3.8/http/client.py", line 951, in send self.connect() File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 187, in connect conn = self._new_conn() File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 171, in _new_conn raise NewConnectionError( urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x7f2a6b15ec40>: Failed to establish a new connection: [Errno -2] Name or service not known During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/requests/adapters.py", line 439, in send resp = conn.urlopen( File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 719, in urlopen retries = retries.increment( File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 436, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host='$%7bnexran_xapp%7d', port=8000): Max retries exceeded with url: /v1/slices/fast (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2a6b15ec40>: Failed to establish a new connection: [Errno -2] Name or service not known')) During handling of the above exception, another exception occurred: Traceback (most recent call last): File "change_slice_allocation.py", line 14, in <module> response1 = requests.put('http://${NEXRAN_XAPP}:8000/v1/slices/fast', headers=headers, data=data1) File "/usr/lib/python3/dist-packages/requests/api.py", line 131, in put return request('put', url, data=data, **kwargs) File "/usr/lib/python3/dist-packages/requests/api.py", line 60, in request return session.request(method=method, url=url, **kwargs) File "/usr/lib/python3/dist-packages/requests/sessions.py", line 533, in request resp = self.send(prep, **send_kwargs) File "/usr/lib/python3/dist-packages/requests/sessions.py", line 646, in send r = adapter.send(request, **kwargs) File "/usr/lib/python3/dist-packages/requests/adapters.py", line 516, in send raise ConnectionError(e, request=request) requests.exceptions.ConnectionError: HTTPConnectionPool(host='$%7bnexran_xapp%7d', port=8000): Max retries exceeded with url: /v1/slices/fast (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f2a6b15ec40>: Failed to establish a new connection: [Errno -2] Name or service not known'))
问题分析与修复
核心问题
- os.system无法传递环境变量到Python进程:通过
os.system执行的export命令仅在子shell中生效,Python主进程无法读取到NEXRAN_XAPP变量。 - Python字符串不解析shell变量:代码中的
'http://${NEXRAN_XAPP}:8000/...'是普通字符串,Python不会将${NEXRAN_XAPP}替换为实际IP,导致请求地址变成无效的$%7bnexran_xapp%7d。 - JSON数据传递方式不够规范:直接传递字符串
data虽然可行,但使用json参数更简洁,requests会自动设置正确的Content-Type头。
修复后的脚本
import requests import subprocess # 获取NEXRAN_XAPP的ClusterIP,用subprocess捕获命令输出 result = subprocess.run( ["sudo", "kubectl", "get", "svc", "-n", "ricxapp", "--field-selector", "metadata.name=service-ricxapp-nexran-rmr", "-o", "jsonpath='{.items[0].spec.clusterIP}'"], capture_output=True, text=True ) # 处理输出,去掉多余的单引号 nexran_xapp_ip = result.stdout.strip().strip("'") # 定义请求数据(用Python字典,方便维护) payload_slow = { "allocation_policy": { "type": "proportional", "share": 1024 } } payload_fast = { "allocation_policy": { "type": "proportional", "share": 256 } } # 发送PUT请求,用json参数自动处理序列化和头部 response_slow = requests.put(f"http://{nexran_xapp_ip}:8000/v1/slices/slow", json=payload_slow) response_fast = requests.put(f"http://{nexran_xapp_ip}:8000/v1/slices/fast", json=payload_fast) # 可选:打印响应信息 print(f"Slow slice response: {response_slow.status_code}") print(f"Fast slice response: {response_fast.status_code}")
关键改进点
- 使用
subprocess.run替代os.system,直接捕获kubectl命令的输出结果,无需依赖环境变量传递。 - 用Python字典定义请求数据,通过
json参数传给requests,自动完成JSON序列化和Content-Type头设置。 - 使用f-string格式化URL,将获取到的IP地址正确插入到请求路径中。
- 保留原Curl中的
sudo(如果执行脚本需要权限的话),避免权限问题。
内容的提问来源于stack exchange,提问作者Black Dagger
相关产品推荐
相关产品推荐

