Interactive Bash Script for Quick Kubernetes Pod Access
This script checks for kubectl, validates the kubeconfig, lets you choose a namespace and pod, selects a shell, and then runs kubectl exec to open an interactive terminal inside the chosen Kubernetes pod.
This Bash script provides an interactive way to access a Kubernetes pod's terminal.
It first checks whether the kubectl command is available; if not, it prints an error and exits. It then verifies that the user's kubeconfig file ( ~/.kube/config) exists, prompting the user to obtain it from operations if missing.
The script prompts the user to choose a namespace (test or stg) and sets the corresponding namespace variable. It asks for a keyword to filter pods, lists matching pods, and asks the user to paste the full pod name.
Next, it asks the user to select a shell (bash or sh) and executes kubectl exec -it with the chosen namespace, pod name, and shell. If the user enters an invalid option, the script displays an error message.
All user prompts and conditional logic are implemented with read -p, case statements, and if checks.
Full script:
#!/bin/bashwhich kubectl > /dev/null 2>&1if [ $? != 0 ];thenecho "kubelet工具未安装,请先安装!!"exitfiif [ ! -f ~/.kube/config ];thenecho "当前用户家目录下没有k8s集群配置文件.kube/config,请联系运维获取配置!"exitfiread -p $'请选择要操作的命名空间:
1: test
2: stg:
' NAMESPACEcase $NAMESPACE in1)NAMESPACE=zzmed-test;;2)NAMESPACE=zzmed-stg;;*)echo "请选择正确的命名空间1:test 2:stg";;esacread -p $'请输入要操作POD的关键字:
' PODkubectl get pods -n $NAMESPACE -owide|grep $PODread -p $'请复制粘贴上方POD的全名,并回车:
' PODNAMEread -p $'请选择要操作的终端:
1: bash
2: sh:
' BASHcase $BASH in1)BASH=bash;;2)BASH=sh;;*)echo "请输入正确的终端1: bash 2: sh";;esackubectl exec -it -n $NAMESPACE $PODNAME $BASHSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
