Kubernetes pod exec using python client not very interactive

1/27/2022

I am following the official example to exec into a Kubernetes container using the python kubernetes-client library.

from kubernetes import config
from kubernetes.client.api import core_v1_api
from kubernetes.stream import stream


def exec_commands(api_instance):

    resp = stream(api_instance.connect_get_namespaced_pod_exec,
                  'busybox',
                  'default',
                  command=['/bin/sh'],
                  stderr=True, stdin=True,
                  stdout=True, tty=True,
                  _preload_content=False)

    while resp.is_open():
        resp.update(timeout=1)
        if resp.peek_stdout():
            print("%s" % resp.read_stdout())
        if resp.peek_stderr():
            print("%s" % resp.read_stderr())

        command = input()

        if command == "exit":
            break
        else:
            resp.write_stdin(command + "\n")

    resp.close()


def main():
    config.load_kube_config("~/.kube/config")
    core_v1 = core_v1_api.CoreV1Api()
    exec_commands(core_v1)


if __name__ == '__main__':
    main()

The above code is able to exec into the container. However, the shell is not very interactive. The issues with it are:-

  1. Arrow keys do not work. When pressing arrows, exec shows ^[[D^[[C^[[A^[[B characters
  2. Tab auto-complete does not work. When I press tab character, it takes tab as input white spaces instead of auto-completing.
  3. I have to hit the enter key twice to get the command output. Example:-

    ls
    
    
    / # ls
    abc.txt       etc           root          tmp
    bin           home          sys           usr
    dev           proc          terminfo.src  var
    / # 
  4. Cannot work with vi editor inside the container because of not been able to use arrow and escape key. Example:-

first line
^[[C^[[D^[[C^[[B

Is there any better way to exec into a kubernetes container programmatically using python?

-- Geek-bit
containers
exec
kubernetes
kubernetes-pod
python

1 Answer

1/27/2022

I am not able to add comment so will reply here.

I suggest looking into readline or curses for properly handling arrow keys and other terminal related issues.

first line
^[[C^[[D^[[C^[[B

You are seeing this because the terminal uses escape sequences to properly handle the arrow keys. print("%s" % resp.read_stdout()) this combo most probably does not handle that well, that's why you see part of the escape sequence and some other letters.

Might I suggest looking into pipes. That way you will not be passing your input/output through print and read_stdout functions, which are more suitable for strings and not terminals.

-- david tsulaia
Source: StackOverflow