获取K8s节点Shell

登录 Pod 所在节点的 Shell 脚本

#!/usr/bin/env bash
#
# author: liy
# filename: entry_node.sh

if [ $# -lt 1 ];then
    printf "Usage: %s <Pod> [Namespace]\n" "$0"
    printf "    The pod parameter is the name of the target pod that needs to be debugged\n"
    printf "    The namespace paramater is the namespace where the target pod is located\n"
    exit 1
fi

for cmd in jq
do
    which $cmd &>/dev/null
    if [ $? -ne 0 ];then
        echo "$cmd command not found"
        exit
    fi
done

pod="$1"
namespace="${2:-default}"
nodename="$(kubectl get pod $pod -n $namespace -o json | jq -r '.spec.nodeName')"
cmd='[ "nsenter", "--target", "1", "--mount", "--uts", "--ipc", "--net", "--pid", "--", "bash"]'
container_id="$(kubectl get pod $pod -n $namespace -o json | jq -r '.status.containerStatuses[].containerID')"
container_id="${container_id/containerd:\/\/}"
pod="kube-nodeshell-$(env LC_ALL=C tr -dc a-z0-9 </dev/random | head -c 6)"
template='{"spec": {"nodeName": "'"$nodename"'","hostPID": true,"hostNetwork": true,"containers": [{"securityContext": {"privileged": true},"image": "alpine","name": "nsenter","stdin": true,"stdinOnce": true,"tty": true,"command": '$cmd', "env": [{"name": "container_id", "value": "'"$container_id"'"}]}],"tolerations": [{"operator": "Exists"}]}}'

kubectl -n $namespace run --image=docker.m.daocloud.io/alpine:3.15 --restart=Never --rm --overrides="$template" -it $pod

posted @ 2022-06-10 14:08  liy36  阅读(308)  评论(0)    收藏  举报