无法在kubernetes pod中执行命令

dnph8jn4  于 5个月前  发布在  Kubernetes
关注(0)|答案(2)|浏览(102)

Python版本3.8.10 Kubernetes版本23.3.0
我正在尝试使用python在kubernetes中的特定pod中运行命令。我已经尝试尽可能减少代码,所以我正在运行这个。

from kubernetes import client, config

config.load_kube_config()

v1 = client.CoreV1Api()
response = v1.connect_get_namespaced_pod_exec(pod_name , namespace, command="df -h", stderr=True, stdin=True, stdout=True, tty=True)
print(response)

字符串
但不管用。我得到的回应是。

kubernetes.client.exceptions.ApiException: (400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Audit-Id': '511c23ce-03bb-4b52-a559-3f354fc80235', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Fri, 18 Mar 2022 18:06:11 GMT', 'Content-Length': '139'})
HTTP response body: {"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"Upgrade request required","reason":"BadRequest","code":400}


如果我运行list all pods的典型示例。它工作正常。所以,它不应该是一个配置问题。我在过去的herehere中读到过这个问题。但我认为它不可能是,由于它们是封闭的问题。
如果我运行k9s shell请求,我可以毫无问题地连接pod。这是我在执行/usr/bin/kubectl --context gke_cloudpak_europe-west2-xxxxx exec -it -n namespace_name pod_name -c rt -- sh -c command -v bash >/dev/null && exec bash || exec sh时在ps a中看到的。
另一个更新,我发现这个info。在最后的页面有一段说。

Why Exec/Attach calls doesn’t work
Starting from 4.0 release, we do not support directly calling exec or attach calls. you should use stream module to call them. so instead of resp = api.connect_get_namespaced_pod_exec(name, ... you should call resp = stream(api.connect_get_namespaced_pod_exec, name, ....

Using Stream will overwrite the requests protocol in core_v1_api.CoreV1Api() This will cause a failure in non-exec/attach calls. If you reuse your api client object, you will need to recreate it between api calls that use stream and other api calls.


我试过这样做,但结果是一样的:(
知道我哪里做错了吗
多谢你的帮助。
问候

hgc7kmma

hgc7kmma1#

是的,这个官方指南说你应该使用resp = **stream**(api.connect_get_namespaced_pod_exec(name, ...
所以你必须像这样编辑你的代码:

...
from kubernetes.stream import stream
...
v1 = client.CoreV1Api()
response = stream(v1.connect_get_namespaced_pod_exec, pod_name , namespace, command="df -h", stderr=True, stdin=True, stdout=True, tty=True)
print(response)

字符串

e5nqia27

e5nqia272#

如果你愿意尝试不同的Python Kubernetes库,kr8s支持这个库,而不需要担心底层HTTP传输的细节。

from kr8s.objects import Pod
response = Pod.get(pod_name, namespace).exec(["df", "-h"])
print(response.stdout.decode())

字符串

相关问题