HAOJX

k8s中如何远程执行pod命令

字数统计: 150阅读时长: 1 min
2021/12/30 Share

example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import (
"fmt"
v1 "k8s.io/api/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/remotecommand"
"log"
"os"
)

config, err := clientcmd.BuildConfigFromFlags("", "config")
if err != nil {
log.Fatal(err)
}
//config.Insecure=true
client, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
option := &v1.PodExecOptions{
Container:"nginx",
Command: []string{"sh","-c","ls"},
Stdin: true,
Stdout: true,
Stderr: true,
}

req:=client.CoreV1().RESTClient().Post().Resource("pods").
Namespace("default").
Name("deploy-nginx-5745bb45d7-b7wsv").
SubResource("exec").VersionedParams(
option,
scheme.ParameterCodec,
)
fmt.Println(req.URL())


exec,err:=remotecommand.NewSPDYExecutor(config,"POST",
req.URL())
if err!=nil{
log.Fatal(err)
}
err=exec.Stream(remotecommand.StreamOptions{
Stdin:os.Stdin,
Stdout:os.Stdout,
Stderr:os.Stderr,
Tty:true,
})
if err!=nil{
log.Fatal(err)
}
CATALOG