kt14
kt14

Reputation: 846

How to attach a interactive shell in Kubernetes using Python Client

I am trying to understand on how we can start a interactive shell on a desired container using Kubernetes client-python API.

I found that we can use connect_get_namespaced_pod_exec to run individual commands.

Is there any way we can start a bash session on the desired pod and do somestuff specifically on the pod(I am using Docker Container)

Any help is most welcome.

Upvotes: 1

Views: 4486

Answers (2)

import sys,os
sys.path.append(os.getcwd())
import lib.debug as debug
debug.init()
from threading import Thread
import shared.kube as kube
from kubernetes.stream import stream
import tty 
import termios

core_api = kube.get_client().get_core_api()


#open stream
resp = stream(core_api.connect_get_namespaced_pod_exec,
                          "nsctl-0",
                          "gs-cluster",
                          command="/bin/bash",
                          stderr=True,
                          stdin=True,
                          stdout=True,
                          tty=True, _preload_content=False)

#redirect input
def read():
    #resp.write_stdin("stty rows 45 cols 130\n")
    while resp.is_open():
        char = sys.stdin.read(1)
        resp.update()
        if resp.is_open():
            resp.write_stdin(char)

t = Thread(target=read, args=[])

#change tty mode to be able to work with escape characters
stdin_fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(stdin_fd)
try:
    tty.setraw(stdin_fd)
    t.start()
    while resp.is_open():
        data = resp.read_stdout(10)
        if resp.is_open():
            if len(data or "")>0:
                sys.stdout.write(data)
                sys.stdout.flush()
finally:
    #reset tty 
    print("\033c")
    termios.tcsetattr(stdin_fd, termios.TCSADRAIN, old_settings)
    print("press enter") 

Upvotes: 0

pagid
pagid

Reputation: 13867

from reading the tests I'd guess that the linked documentation already holds your answer. Use /bin/bash as command and send any further commands through the stdin stream.

Invokation should be done with:

api.connect_get_namespaced_pod_exec('pod',
                                   'namespace',
                                    command='/bin/bash'
                                    stderr=True,
                                    stdin=True,
                                    stdout=True,
                                    tty=True)

The related kubectl exec --tty ... client code is implemented the same way and could be used as a reference too.

Upvotes: 3

Related Questions