kubectl 常见命令
登录命令
根据机器ip使用kubectl登录机器(field-selector):
#!/bin/bash
export targetIp="6.0.90.240"#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'podinfo=`kubectl get pod --all-namespaces --field-selector=status.podIP="$targetIp" -o wide | grep -v NAME | head -n 1 `
ns=`echo ${podinfo} | awk '{print $1}'`
pod=`echo ${podinfo} | awk '{print $2}'`echo "$kubectl exec -it -n ${ns} ${pod} -- su - root"
kubectl exec -it -n ${ns} ${pod} -- su - root
根据机器ip使用kubectl登录机器(label):
#!/bin/bash
export targetIp="6.3.144.241"#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'podinfo=`kubectl get pod --all-namespaces -l sigma.ali/ip="$targetIp" -o wide | grep -v NAMESPACE`
ns=`echo ${podinfo} | awk '{print $1}'`
pod=`echo ${podinfo} | awk '{print $2}'`echo "$kubectl exec -it -n ${ns} ${pod} -- su - root"
kubectl exec -it -n ${ns} ${pod} -- su - root
更智能版本的kubectl登录命令:
- 查看KUBECONFIG_DIR目录下有哪些kubeconfig可以用
- 校验目标登录的ip格式
- 查询并解析pod信息
- 查询该pod有哪些容器并展示
- 查询选定的容器有哪些用户(与user_array做交集),支持自定义输入用户
- 根据以上信息登录目标ip对应pod的选定容器
#!/bin/bash# 添加特定用户
user_array=("root" "admin" "log")# 从指定目录获取所有 kubeconfig 文件
KUBECONFIG_DIR="/Users/king/.kube"# 初始化 kubectl 命令前缀
KUBECTL_CMD="kubectl"# 确保将信息打印到终端里,即使在函数之间$(...)调用的场景
function print_to_console() {printf "%s\n" "$1" >&2
}# 检查IP地址是否符合正确的格式
function is_valid_ip() {local ip=$1local valid_regex='^([0-9]{1,3}\.){3}[0-9]{1,3}$'if [[ $ip =~ $valid_regex ]]; then# 确保每个数字部分小于等于255IFS='.' read -r -a octets <<< "$ip"for octet in "${octets[@]}"; doif ((octet > 255)); thenreturn 1fidonereturn 0fireturn 1
}KUBECONFIGS=($(find $KUBECONFIG_DIR -maxdepth 1 -name "*.config" -print))# 检查是否找到 kubeconfig 文件
if [ ${#KUBECONFIGS[@]} -eq 0 ]; thenprint_to_console "没有找到任何 kubeconfig 文件在目录: $KUBECONFIG_DIR"
else# 提供给用户选择的菜单,动态生成选项范围提示cat << EOF----------------------------------------------|*******Please Enter Your Choice:[1-${#KUBECONFIGS[@]}]*******|----------------------------------------------
EOF# 输出可供选择的配置文件选项for i in "${!KUBECONFIGS[@]}"; doprint_to_console "* $(($i + 1)) ${KUBECONFIGS[$i]}"done# 捕获用户输入并确保在合法范围内while true; doread -p "please input your choice [1-${#KUBECONFIGS[@]}] (or press Enter to skip): " numif [[ -z "$num" ]]; thenbreakelif [[ "$num" =~ ^[0-9]+$ ]] && [ "$num" -ge 1 ] && [ "$num" -le ${#KUBECONFIGS[@]} ]; thenselected_config="${KUBECONFIGS[$((num - 1))]}"KUBECTL_CMD="kubectl --kubeconfig=$selected_config"print_to_console "Using configuration file: $selected_config"breakelseprint_to_console "Invalid choice. Please try again."fidone
fi# 输出用户选择的配置文件
selected_config="${KUBECONFIGS[$((num - 1))]}"
print_to_console "You selected: $selected_config"# 捕获用户输入的targetIP
while true; doread -p "please input your target ip: " targetIP# 检查输入是否为空和格式有效性if [[ -z "$targetIP" ]]; thenprint_to_console "IP 地址不能为空,请重新输入。"elif ! is_valid_ip "$targetIP"; thenprint_to_console "无效的IP格式,请输入有效的IP地址。"elseprint_to_console "您输入的IP地址是: $targetIP"breakfi
done# 获取 Pod 信息
podinfo=$($KUBECTL_CMD get pod --all-namespaces --field-selector=status.podIP="$targetIP" -o wide | grep -v NAME | head -n 1)# 检查 podinfo 是否为空
if [[ -z "$podinfo" ]]; thenprint_to_console "未能获取到对应 IP 的 Pod 信息,退出脚本。"exit 1
fi# 提取命名空间和 Pod 名称
ns=$(echo "${podinfo}" | awk '{print $1}')
pod=$(echo "${podinfo}" | awk '{print $2}')# 检查 ns 和 pod 是否为空
if [[ -z "$ns" || -z "$pod" ]]; thenprint_to_console "未能提取到命名空间或 Pod 名称,退出脚本。"exit 1
fiprint_to_console "Namespace: $ns, Pod: $pod"# 获取容器列表
containers=($($KUBECTL_CMD get pod $pod -n $ns -o jsonpath='{.spec.containers[*].name}'))
selected_container=""
if [ ${#containers[@]} -gt 0 ]; thenprint_to_console "请选择一个容器 (或直接按 Enter 跳过使用默认容器):"for i in "${!containers[@]}"; doprint_to_console "* $(($i + 1)) ${containers[$i]}"donewhile true; doread -p "please input your choice [1-${#containers[@]}] (or press Enter to skip): " container_numif [[ -z "$container_num" ]]; thenbreakelif [[ "$container_num" =~ ^[0-9]+$ ]] && [ "$container_num" -ge 1 ] && [ "$container_num" -le ${#containers[@]} ]; thenselected_container="${containers[$((container_num - 1))]}"print_to_console "Selected container: $selected_container"breakelseprint_to_console "Invalid choice. Please try again."fidone
fi# 解析容器中的用户并添加到用户数组中
while IFS=: read -r username _ uid _; doif [[ $uid -ge 1000 && $username != "nobody" ]]; thenuser_array+=("$username")fi
done <<< "$user_list"# 显示可供选择的用户列表
print_to_console "请选择一个用户 (或自定义输入):"
for i in "${!user_array[@]}"; doprint_to_console "* $(($i + 1)) ${user_array[$i]}"
done
print_to_console "* $(( ${#user_array[@]} + 1 )) 自定义输入 "# 捕获用户选择的用户
while true; doread -p "please input your choice [1-$(( ${#user_array[@]} + 1 ))]: " user_numif [[ "$user_num" =~ ^[0-9]+$ ]] && [ "$user_num" -ge 1 ] && [ "$user_num" -le $(( ${#user_array[@]} + 1 )) ]; thenif [ "$user_num" -eq $(( ${#user_array[@]} + 1 )) ]; thenread -p "请输入自定义用户名: " targetUserelsetargetUser="${user_array[$((user_num - 1))]}"fiprint_to_console "Selected user: $targetUser"breakelseprint_to_console "Invalid choice. Please try again."fi
done# 执行命令
if [[ -n "$selected_container" ]]; thenprint_to_console "$KUBECTL_CMD exec -it -n ${ns} ${pod} -c ${selected_container} -- su - $targetUser"$KUBECTL_CMD exec -it -n ${ns} ${pod} -c ${selected_container} -- su - $targetUser
elseprint_to_console "$KUBECTL_CMD exec -it -n ${ns} ${pod} -- su - $targetUser"$KUBECTL_CMD exec -it -n ${ns} ${pod} -- su - $targetUser
fi
查询命令
根据机器ip(field-selector)查询pod:
#!/bin/bash
export fieldKEY="status.podIP"
export fieldVALUE="6.0.90.240"#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'kubectl get pod --all-namespaces --field-selector=$fieldKEY=$fieldVALUE -o wide
根据label查询pod:
#!/bin/bash
export labelKEY="sigma.ali/ip"
export labelVALUE="6.0.90.240"#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'kubectl get pod --all-namespaces -l $labelKEY=$labelVALUE -o wide
导出yaml
根据机器ip使用kubectl导出机器yaml:
#!/bin/bash
local podName=""
local namespace=""#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'kubectl get pod/$podName -n ${namespace} -oyaml
describe
根据namespace和podName进行describe
local namespace="longtermbase"
local podName="inplaceset-antcodebuild-tn1oimjfl-gz00b-0"#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'kubectl describe pod $podName -n $namespace
清理terminating的pod
通过清理finalizers实现
local namespace=""
local podName=""#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'kubectl patch pod/$podName -n $namespace -p '{"metadata":{"finalizers":null}}'
强制删除
local namespace=""
local podName=""#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'k delete pod/$podName -n $namespace --force --grace-period=0
复制文件到pod容器
local namespace=""
local podName=""
local sourceDir=""
local sourceFile=""
local targetDir=""
local targetFile=""#alias kubectl='kubectl'
alias kubectl='kubectl --kubeconfig=/Users/king/.kube/sa128.config'kubectl cp -n linkw $sourceDir/$sourceFile $podName:/targetDir/targetFile