Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Kubectl exec into Kube-monkey pod #226

Open
k8sVoodoo opened this issue Feb 15, 2022 · 0 comments
Open

Kubectl exec into Kube-monkey pod #226

k8sVoodoo opened this issue Feb 15, 2022 · 0 comments

Comments

@k8sVoodoo
Copy link

Could you append this func into your main.go and update the go.sum?? I believe this will fix the issue trying to kubectl exec into the pod to check the config.toml and anything else within the pod.
##################################################################################

import (
  "bytes"
  "fmt"

  v1 "k8s.io/api/core/v1"
  metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  "k8s.io/client-go/kubernetes"
  "k8s.io/client-go/kubernetes/scheme"
  "k8s.io/client-go/tools/clientcmd"
  "k8s.io/client-go/tools/remotecommand"
)

func ExecuteRemoteCommand(pod *v1.Pod, command string) (string, string, error) {
  kubeCfg := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
    clientcmd.NewDefaultClientConfigLoadingRules(),
    &clientcmd.ConfigOverrides{},
  )
  restCfg, err := kubeCfg.ClientConfig()
  if err != nil {
    return "", "", err
  }
  coreClient, err := kubernetes.NewForConfig(restCfg)
  if err != nil {
    return "", "", err
  }

  buf := &bytes.Buffer{}
  errBuf := &bytes.Buffer{}
  request := coreClient.CoreV1().RESTClient().
    Post().
    Namespace(pod.Namespace).
    Resource("pods").
    Name(pod.Name).
    SubResource("exec").
    VersionedParams(&v1.PodExecOptions{
      Command: []string{"/bin/sh", "-c", command},
      Stdin:   false,
      Stdout:  true,
      Stderr:  true,
      TTY:     true,
    }, scheme.ParameterCodec)
  exec, err := remotecommand.NewSPDYExecutor(restCfg, "POST", request.URL())
  err = exec.Stream(remotecommand.StreamOptions{
    Stdout: buf,
    Stderr: errBuf,
  })
  if err != nil {
    return "", "", fmt.Errorf("%w Failed executing command %s on %v/%v", err, command, pod.Namespace, pod.Name)
  }

  return buf.String(), errBuf.String(), nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant