python实现获取k8s的pod信息

发布于:2025-08-07 ⋅ 阅读:(16) ⋅ 点赞:(0)

目录

1. 依赖

2. 代码

3. 执行代码

4. 效果


1. 依赖

#requirements.txt
kubernetes>=28.1.0

2. 代码

#!/usr/bin/env python3
"""
Kubernetes Pod信息查看脚本
查看monitor命名空间下的所有Pod信息
"""
​
import os
from kubernetes import client, config
from kubernetes.client.rest import ApiException
import json
from datetime import datetime
​
​
def load_k8s_config():
    """加载Kubernetes配置"""
    try:
        # 尝试从kubeconfig文件加载配置
        config.load_kube_config()
        print("✓ 已从kubeconfig文件加载配置")
    except Exception:
        try:
            # 尝试从集群内部加载配置
            config.load_incluster_config()
            print("✓ 已从集群内部加载配置")
        except Exception as e:
            print(f"✗ 无法加载Kubernetes配置: {e}")
            return False
    return True
​
​
def get_pods_in_namespace(namespace="monitor"):
    """获取指定命名空间下的所有Pod信息"""
    try:
        # 创建API客户端
        v1 = client.CoreV1Api()
        
        print(f"\n正在获取 {namespace} 命名空间下的Pod信息...")
        
        # 获取Pod列表
        pods = v1.list_namespaced_pod(namespace=namespace)
        
        if not pods.items:
            print(f"在 {namespace} 命名空间下没有找到Pod")
            return []
        
        print(f"✓ 找到 {len(pods.items)} 个Pod")
        
        pod_info_list = []
        
        for pod in pods.items:
            pod_info = {
                "name": pod.metadata.name,
                "namespace": pod.metadata.namespace,
                "status": pod.status.phase,
                "ready": "Ready" if pod.status.conditions else "Not Ready",
                "restarts": pod.status.container_statuses[0].restart_count if pod.status.container_statuses else 0,
                "age": pod.metadata.creation_timestamp,
                "ip": pod.status.pod_ip,
                "node": pod.spec.node_name,
                "containers": []
            }
            
            # 获取容器信息
            if pod.status.container_statuses:
                for container in pod.status.container_statuses:
                    container_info = {
                        "name": container.name,
                        "image": container.image,
                        "ready": container.ready,
                        "restart_count": container.restart_count,
                        "state": str(container.state)
                    }
                    pod_info["containers"].append(container_info)
            
            pod_info_list.append(pod_info)
        
        return pod_info_list
        
    except ApiException as e:
        print(f"✗ API错误: {e}")
        return []
    except Exception as e:
        print(f"✗ 获取Pod信息时发生错误: {e}")
        return []
​
​
def display_pod_info(pod_info_list):
    """显示Pod信息"""
    if not pod_info_list:
        return
    
    print(f"\n{'='*80}")
    print(f"MONITOR命名空间Pod信息 - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"{'='*80}")
    
    for i, pod in enumerate(pod_info_list, 1):
        print(f"\n{i}. Pod名称: {pod['name']}")
        print(f"   命名空间: {pod['namespace']}")
        print(f"   状态: {pod['status']}")
        print(f"   就绪状态: {pod['ready']}")
        print(f"   重启次数: {pod['restarts']}")
        print(f"   创建时间: {pod['age']}")
        print(f"   Pod IP: {pod['ip']}")
        print(f"   节点: {pod['node']}")
        
        if pod['containers']:
            print(f"   容器信息:")
            for j, container in enumerate(pod['containers'], 1):
                print(f"     {j}. {container['name']}")
                print(f"        镜像: {container['image']}")
                print(f"        就绪: {container['ready']}")
                print(f"        重启次数: {container['restart_count']}")
                print(f"        状态: {container['state']}")
​
​
def save_to_json(pod_info_list, filename="monitor_pods.json"):
    """将Pod信息保存到JSON文件"""
    if not pod_info_list:
        return
    
    try:
        # 转换datetime对象为字符串
        for pod in pod_info_list:
            if pod['age']:
                pod['age'] = pod['age'].isoformat()
        
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(pod_info_list, f, ensure_ascii=False, indent=2)
        
        print(f"\n✓ Pod信息已保存到 {filename}")
    except Exception as e:
        print(f"✗ 保存文件时发生错误: {e}")
​
​
def main():
    """主函数"""
    print("Kubernetes Pod信息查看工具")
    print("=" * 50)
    
    # 加载Kubernetes配置
    if not load_k8s_config():
        return
    
    # 获取Pod信息
    pod_info_list = get_pods_in_namespace("monitor")
    
    # 显示Pod信息
    display_pod_info(pod_info_list)
    
    # 保存到JSON文件
    save_to_json(pod_info_list)
    
    print(f"\n{'='*80}")
    print("脚本执行完成")
​
​
if __name__ == "__main__":
    main()
​

3. 执行代码

pip install -r requirements.txt
python get-pod.py
#python3执行以下代码
python3 get-pod.py

查看其他命名空间的Pod,可以修改脚本中的namespace参数:

pod_info_list = get_pods_in_namespace("your-namespace")

4. 效果

查看monitor名字空间下的pod信息

[root@master1 get-pod]# python3 get-pod.py 
Kubernetes Pod信息查看工具
==================================================
✓ 已从kubeconfig文件加载配置
​
正在获取 monitor 命名空间下的Pod信息...
✓ 找到 16 个Pod
​
================================================================================
MONITOR命名空间Pod信息 - 2025-08-06 23:37:37
================================================================================
​
1. Pod名称: grafana-server-6bf79cb7fc-lnqkd
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 0
   创建时间: 2025-08-06 15:27:04+00:00
   Pod IP: 10.244.137.126
   节点: master1
   容器信息:
     1. grafana
        镜像: 192.168.48.100/prometheus/grafana:latest
        就绪: True
        重启次数: 0
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 27, 4, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
2. Pod名称: kube-state-metrics-5565bbc5ff-d4rrp
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 0
   创建时间: 2025-08-06 15:27:04+00:00
   Pod IP: 10.244.180.27
   节点: master2
   容器信息:
     1. kube-state-metrics
        镜像: quay.io/coreos/kube-state-metrics:latest
        就绪: True
        重启次数: 0
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 27, 4, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
3. Pod名称: loki-0
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 0
   创建时间: 2025-08-06 15:32:40+00:00
   Pod IP: 10.244.196.131
   节点: node01
   容器信息:
     1. loki
        镜像: 192.168.48.100/prometheus/grafana/loki:2.6.1
        就绪: True
        重启次数: 0
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 32, 41, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
4. Pod名称: loki-promtail-7mlwc
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 18:32:36+00:00
   Pod IP: 10.244.186.239
   节点: node03
   容器信息:
     1. promtail
        镜像: 192.168.48.100/prometheus/grafana/promtail:2.9.3
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 31, 40, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
5. Pod名称: loki-promtail-gdjtz
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 18:32:36+00:00
   Pod IP: 10.244.137.86
   节点: master1
   容器信息:
     1. promtail
        镜像: 192.168.48.100/prometheus/grafana/promtail:2.9.3
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 20, 40, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
6. Pod名称: loki-promtail-kjtkk
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 18:32:36+00:00
   Pod IP: 10.244.180.37
   节点: master2
   容器信息:
     1. promtail
        镜像: 192.168.48.100/prometheus/grafana/promtail:2.9.3
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 20, 42, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
7. Pod名称: loki-promtail-n6psz
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 18:32:36+00:00
   Pod IP: 10.244.140.72
   节点: node02
   容器信息:
     1. promtail
        镜像: 192.168.48.100/prometheus/grafana/promtail:2.9.3
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 32, 26, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
8. Pod名称: loki-promtail-qdn9v
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 18:32:36+00:00
   Pod IP: 10.244.196.130
   节点: node01
   容器信息:
     1. promtail
        镜像: 192.168.48.100/prometheus/grafana/promtail:2.9.3
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 31, 32, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
9. Pod名称: loki-promtail-zcbmp
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 0
   创建时间: 2025-08-06 15:20:58+00:00
   Pod IP: 10.244.136.57
   节点: master3
   容器信息:
     1. promtail
        镜像: 192.168.48.100/prometheus/grafana/promtail:2.9.3
        就绪: True
        重启次数: 0
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 20, 59, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
10. Pod名称: node-exporter-7wshk
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 17:52:28+00:00
   Pod IP: 192.168.48.105
   节点: node02
   容器信息:
     1. node-exporter
        镜像: prom/node-exporter:latest
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 31, 30, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
11. Pod名称: node-exporter-99rz7
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 17:52:28+00:00
   Pod IP: 192.168.48.104
   节点: node01
   容器信息:
     1. node-exporter
        镜像: prom/node-exporter:latest
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 31, 31, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
12. Pod名称: node-exporter-cvrms
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 17:52:28+00:00
   Pod IP: 192.168.48.101
   节点: master1
   容器信息:
     1. node-exporter
        镜像: prom/node-exporter:latest
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 20, 41, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
13. Pod名称: node-exporter-qd5hz
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 17:52:28+00:00
   Pod IP: 192.168.48.106
   节点: node03
   容器信息:
     1. node-exporter
        镜像: prom/node-exporter:latest
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 31, 41, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
14. Pod名称: node-exporter-stjwr
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 17:52:28+00:00
   Pod IP: 192.168.48.103
   节点: master3
   容器信息:
     1. node-exporter
        镜像: prom/node-exporter:latest
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 20, 39, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
15. Pod名称: node-exporter-sxdf2
   命名空间: monitor
   状态: Running
   就绪状态: Ready
   重启次数: 1
   创建时间: 2025-08-05 17:52:28+00:00
   Pod IP: 192.168.48.102
   节点: master2
   容器信息:
     1. node-exporter
        镜像: prom/node-exporter:latest
        就绪: True
        重启次数: 1
        状态: {'running': {'started_at': datetime.datetime(2025, 8, 6, 15, 20, 41, tzinfo=tzutc())},
 'terminated': None,
 'waiting': None}
​
16. Pod名称: prometheus-alertmanager-5758b69574-prhdb
   命名空间: monitor
   状态: Pending
   就绪状态: Ready
   重启次数: 0
   创建时间: 2025-08-06 15:26:54+00:00
   Pod IP: 10.244.136.4
   节点: master3
   容器信息:
     1. alertmanager
        镜像: prom/alertmanager:v0.23.0
        就绪: False
        重启次数: 0
        状态: {'running': None,
 'terminated': None,
 'waiting': {'message': None, 'reason': 'PodInitializing'}}
     2. prometheus
        镜像: 192.168.48.100/prometheus/prometheus:latest
        就绪: False
        重启次数: 0
        状态: {'running': None,
 'terminated': None,
 'waiting': {'message': None, 'reason': 'PodInitializing'}}
​
✓ Pod信息已保存到 monitor_pods.json
​
================================================================================
脚本执行完成

同时生成了pod信息的json文件

[root@master1 get-pod]# ls
get-pod.py  monitor_pods.json  README.md  requirements.txt

网站公告

今日签到

点亮在社区的每一天
去签到