繁体   English   中英

如何在 python k8s 客户端中以 root 身份运行“connect_get_namespaced_pod_exec”

[英]How to run 'connect_get_namespaced_pod_exec' as root in python k8s client

from os import getenv, listdir, path
from kubernetes import client, config
from kubernetes.stream import stream
import constants, logging
from pprint import pprint

def listdir_fullpath(directory):
    return [path.join(directory, file) for file in listdir(directory)]

def active_context(kubeConfig, cluster):
    config.load_kube_config(config_file=kubeConfig, context=cluster)

def kube_exec(command, apiInstance, podName, namespace, container):
    response = None
    execCommand = [
        '/bin/bash',
        '-c',
        command]
    try:
        response = apiInstance.read_namespaced_pod(name=podName,
                                                namespace=namespace)
    except ApiException as e:
        if e.status != 404:
            print(f"Unknown error: {e}")
            exit(1)
    if not response:
        print("Pod does not exist")
        exit(1)
    try:
        response = stream(apiInstance.connect_get_namespaced_pod_exec,
                          podName,
                          namespace,
                          container=container,
                          command=execCommand,
                          stderr=True,
                          stdin=False,
                          stdout=True,
                          tty=False,
                          _preload_content=True)
    except Exception as e:
        print("error in executing cmd")
        exit(1)
    pprint(response)


if __name__ == '__main__':
    configPath     = constants.CONFIGFILE
    kubeConfigList = listdir_fullpath(configPath)
    kubeConfig = ':'.join(kubeConfigList)
    active_context(kubeConfig, "ort.us-west-2.k8s.company-foo.net")
    apiInstance = client.CoreV1Api()
    kube_exec("whoami", apiInstance, "podname-foo", "namespace-foo", "container-foo")

我运行这段代码,运行whoami得到的响应是: 'java\n'我如何以 root 身份运行? 另外,我在任何地方都找不到这个客户的好文档(git repo 上的文档非常糟糕)如果你能把我链接到任何地方,那就太棒了

编辑:我刚刚尝试了几个不同的 pod 和容器,看起来其中一些默认为 root,仍然希望能够在我运行命令时选择我的用户,所以问题仍然相关

其中一些默认为 root,当我运行命令时仍然希望能够选择我的用户,所以问题仍然相关

当您启动Pod 时,您对 UID 有影响(据我所知,不是直接影响用户),但从那时起,在 kubernetes 中没有与docker exec -u等效的东西——您可以附加到 Pod,以启动时的任何 UID 运行,但您无法更改 UID

我假设这是锁定集群中的一个安全问题,因为人们不希望具有 kubectl 访问权限的人能够提升权限

如果您需要在容器中以root身份运行,则应更改securityContext: runAsUser: 0的值,然后删除运行主进程的权限。 这样,新命令(由您的exec命令生成)将以 root 身份运行,就像您的初始command:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM