使用 go 客户端在 k8s 的 pod 中执行 exec 的示例

JJB*_*oom 11 kubernetes

我想使用 k8s go 客户端在 pod 中执行命令。但是,我找不到任何关于此的示例。所以我阅读了kubectl exec源代码,并编写了如下代码。并且err = exec.Stream(sopt)总是在没有任何消息的情况下出现错误。谁能告诉我如何调试这个问题,或者给我一个正确的例子。

config := &restclient.Config{
 Host: "http://192.168.8.175:8080",
Insecure: true,
}

config.ContentConfig.GroupVersion = &api.Unversioned
config.ContentConfig.NegotiatedSerializer = api.Codecs

restClient, err := restclient.RESTClientFor(config)
if err != nil {
  panic(err.Error())
}

req := restClient.Post().Resource("pods").Name("wordpress-mysql-213049546-29s7d").Namespace("default").SubResource("exec").Param("container", "mysql")
req.VersionedParams(&api.PodExecOptions{
Container: "mysql",
Command:   []string{"ls"},
Stdin:     true,
Stdout:    true,
}, api.ParameterCodec)

 exec, err := remotecommand.NewExecutor(config, "POST", req.URL())
 if err != nil {
   panic(err.Error())
}
sopt := remotecommand.StreamOptions{
SupportedProtocols: remotecommandserver.SupportedStreamingProtocols,
Stdin:              os.Stdin,
Stdout: os.Stdout,
Stderr: os.Stderr,
Tty:    false,
}

err = exec.Stream(sopt)
if err != nil {
 panic(err.Error())
}
Run Code Online (Sandbox Code Playgroud)

noa*_*wer 7

package k8s

import (
    "io"

    v1 "k8s.io/api/core/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/kubernetes/scheme"
    restclient "k8s.io/client-go/rest"
    "k8s.io/client-go/tools/remotecommand"
)

// ExecCmd exec command on specific pod and wait the command's output.
func ExecCmdExample(client kubernetes.Interface, config *restclient.Config, podName string,
    command string, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
    cmd := []string{
        "sh",
        "-c",
        command,
    }
    req := client.CoreV1().RESTClient().Post().Resource("pods").Name(podName).
        Namespace("default").SubResource("exec")
    option := &v1.PodExecOptions{
        Command: cmd,
        Stdin:   true,
        Stdout:  true,
        Stderr:  true,
        TTY:     true,
    }
    if stdin == nil {
        option.Stdin = false
    }
    req.VersionedParams(
        option,
        scheme.ParameterCodec,
    )
    exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
    if err != nil {
        return err
    }
    err = exec.Stream(remotecommand.StreamOptions{
        Stdin:  stdin,
        Stdout: stdout,
        Stderr: stderr,
    })
    if err != nil {
        return err
    }

    return nil
}
Run Code Online (Sandbox Code Playgroud)

它对我有用。


Yas*_*sha 2

Command: []string{"/bin/sh", "-c", "ls", "-ll", "."}
Run Code Online (Sandbox Code Playgroud)

字符串数组应以/bin/sh(shell 可执行文件的路径) 开头。

然后-c可以添加flag作为第二个元素,以指示后续字符串将被解释为由shell执行的命令。

最后,该命令的任何其他参数都可以添加为数组中的后续元素。