如何使用Python实现K8s集群节点名称与状态的获取及格式化输出?
Got it, let's figure out how to replace your kubectl get nodes | awk workflow with a clean Python script that outputs nodes in the format {node_name} has {status_value}. I'll cover two reliable approaches—one that leverages kubectl directly (no extra dependencies) and another using the official Kubernetes Python client (better for long-term projects).
Approach 1: Use subprocess to Call kubectl (No Extra Packages)
This is perfect if you want a quick script that works with your existing kubectl setup, no extra Python installs required. We'll use kubectl's JSON output to avoid messy text parsing.
import subprocess import json def get_k8s_nodes(): # Run kubectl to get node data in JSON format try: kubectl_output = subprocess.run( ["kubectl", "get", "nodes", "-o", "json"], capture_output=True, text=True, check=True ) nodes_data = json.loads(kubectl_output.stdout) except subprocess.CalledProcessError as e: print(f"Error running kubectl: {e.stderr.strip()}") return [] node_status_list = [] for node in nodes_data["items"]: node_name = node["metadata"]["name"] # Get the node's Ready status (matches kubectl's default output) ready_status = "NotReady" for condition in node["status"]["conditions"]: if condition["type"] == "Ready": if condition["status"] == "True": ready_status = "Ready" elif condition["status"] == "False": ready_status = "NotReady" else: ready_status = condition["status"] # Handles "Unknown" status break node_status_list.append(f"{node_name} has {ready_status}") return node_status_list if __name__ == "__main__": for status_line in get_k8s_nodes(): print(status_line)
Key Notes for This Approach:
- Requires
kubectlto be installed and configured for your cluster (uses your current kubeconfig context). - The script extracts the Ready status (the most critical node status) and formats it to match what
kubectlshows (Ready/NotReady/Unknown).
Approach 2: Use the Official Kubernetes Python Client
For more maintainable, production-ready code (especially if you're building a larger Kubernetes tool), the official client is the way to go.
Step 1: Install the Client
First, install the Kubernetes Python package:
pip install kubernetes
Step 2: The Script
from kubernetes import client, config def get_k8s_nodes(): # Load cluster configuration try: # Use this if running locally (uses ~/.kube/config) config.load_kube_config() # Uncomment below if running inside a Kubernetes pod (uses service account) # config.load_incluster_config() except config.ConfigException: print("Failed to load cluster config. If running in a pod, use load_incluster_config().") return [] # Initialize API client v1_api = client.CoreV1Api() nodes = v1_api.list_node().items node_status_list = [] for node in nodes: node_name = node.metadata.name # Get Ready status ready_status = "NotReady" for condition in node.status.conditions: if condition.type == "Ready": if condition.status == "True": ready_status = "Ready" elif condition.status == "False": ready_status = "NotReady" else: ready_status = condition.status break node_status_list.append(f"{node_name} has {ready_status}") return node_status_list if __name__ == "__main__": for status_line in get_k8s_nodes(): print(status_line)
Key Notes for This Approach:
- If running the script inside a Kubernetes pod, comment out
config.load_kube_config()and uncommentconfig.load_incluster_config()—this uses the pod's mounted service account for authentication. - The client gives you full access to all node metadata and status fields, so you can easily extend this script to fetch additional info (like node CPU, OS, or taints) if needed.
Example Output
Either script will produce output like this:
worker-node-0 has Ready control-plane-0 has Ready worker-node-1 has NotReady
内容的提问来源于stack exchange,提问作者shiva

