如何使用Python Client在Kubernetes中附加交互式shell

mwkjh3gx  于 2024-01-06  发布在  Kubernetes
关注(0)|答案(2)|浏览(157)

我试图了解如何使用Kubernetes client-python API在所需容器上启动交互式shell。
我发现我们可以使用connect_get_namespaced_pod_exec来运行单个命令。
有没有什么方法可以在所需的pod上启动一个bash会话,并在pod上做一些特定的事情(我使用Docker容器)
任何帮助都是最受欢迎的。

oewdyzsn

oewdyzsn1#

通过阅读测试,我猜链接的文档中已经包含了您的答案。
应使用以下命令完成调用:

  1. api.connect_get_namespaced_pod_exec('pod',
  2. 'namespace',
  3. command='/bin/bash'
  4. stderr=True,
  5. stdin=True,
  6. stdout=True,
  7. tty=True)

字符串
相关的kubectl exec --tty ... x1e0f01x以相同的方式实现,也可用作参考。

ecfdbz9o

ecfdbz9o2#

  1. import sys,os
  2. sys.path.append(os.getcwd())
  3. import lib.debug as debug
  4. debug.init()
  5. from threading import Thread
  6. import shared.kube as kube
  7. from kubernetes.stream import stream
  8. import tty
  9. import termios
  10. core_api = kube.get_client().get_core_api()
  11. #open stream
  12. resp = stream(core_api.connect_get_namespaced_pod_exec,
  13. "nsctl-0",
  14. "gs-cluster",
  15. command="/bin/bash",
  16. stderr=True,
  17. stdin=True,
  18. stdout=True,
  19. tty=True, _preload_content=False)
  20. #redirect input
  21. def read():
  22. #resp.write_stdin("stty rows 45 cols 130\n")
  23. while resp.is_open():
  24. char = sys.stdin.read(1)
  25. resp.update()
  26. if resp.is_open():
  27. resp.write_stdin(char)
  28. t = Thread(target=read, args=[])
  29. #change tty mode to be able to work with escape characters
  30. stdin_fd = sys.stdin.fileno()
  31. old_settings = termios.tcgetattr(stdin_fd)
  32. try:
  33. tty.setraw(stdin_fd)
  34. t.start()
  35. while resp.is_open():
  36. data = resp.read_stdout(10)
  37. if resp.is_open():
  38. if len(data or "")>0:
  39. sys.stdout.write(data)
  40. sys.stdout.flush()
  41. finally:
  42. #reset tty
  43. print("\033c")
  44. termios.tcsetattr(stdin_fd, termios.TCSADRAIN, old_settings)
  45. print("press enter")

字符串

展开查看全部

相关问题