Python使用Kubernetes API访问集群


Posted in Python onMay 30, 2021

通过将身份认证令牌直接传给 API 服务器,可以避免使用 kubectl 代理,像这样:
使用 grep/cut 方式:

# 查看所有的集群,因为你的 .kubeconfig 文件中可能包含多个上下文
kubectl config view -o jsonpath='{"Cluster name\tServer\n"}{range .clusters[*]}{.name}{"\t"}{.cluster.server}{"\n"}{end}'

# 从上述命令输出中选择你要与之交互的集群的名称
export CLUSTER_NAME="some_server_name"

# 指向引用该集群名称的 API 服务器
APISERVER=$(kubectl config view -o jsonpath="{.clusters[?(@.name==\"$CLUSTER_NAME\")].cluster.server}")

# 获得令牌
TOKEN=$(kubectl get secrets -o jsonpath="{.items[?(@.metadata.annotations['kubernetes\.io/service-account\.name']=='default')].data.token}"|base64 -d)

# 使用令牌玩转 API
curl -X GET $APISERVER/api --header "Authorization: Bearer $TOKEN" --insecure

客户端库:https://kubernetes.io/zh/docs/reference/using-api/client-libraries/

python举例:

目录结构

Python使用Kubernetes API访问集群

配置文件两种方式

1、将集群中的~/.kube/config,重命名为kubeconfig.yaml
代码:

from kubernetes import  client,config
from kubernetes.stream import stream
import yaml
config_file = r"D:\Users\JackHe\PycharmProjects\JJ\k8s\auth\kubeconfig.yaml"
config.kube_config.load_kube_config(config_file=config_file)
Api_Instance = client.CoreV1Api()
Api_Batch = client.BatchV1Api()

#列出所有的namesapce
for ns in Api_Instance.list_namespace().items:
    print(ns.metadata.name)

#列出所有的nodes
def list_node():
    api_response = Api_Instance.list_node()
    data = {}
    for i in api_response.items:
        data[i.metadata.name] = {"name": i.metadata.name,
                                "status": i.status.conditions[-1].type if i.status.conditions[-1].status == "True" else "NotReady",
                                "ip": i.status.addresses[0].address,
                                "kubelet_version": i.status.node_info.kubelet_version,
                                "os_image": i.status.node_info.os_image,
                                 }
    return data
nodes = list_node()
print(nodes)

2、使用token形式,获取命令上文所示。
代码:

# -*- coding: utf-8 -*-
from kubernetes.client import api_client
from kubernetes.client.apis import core_v1_api
from kubernetes import client,config


class KubernetesTools(object):
    def __init__(self):
        self.k8s_url = 'https://192.168.1.56:6443'

    def get_token(self):
        """
        获取token
        :return:
        """
        with open(r'D:\Users\JackHe\PycharmProjects\JJ\k8s\auth\token', 'r') as file:
            Token = file.read().strip('\n')
            return Token

    def get_api(self):
        """
        获取API的CoreV1Api版本对象
        :return:
        """
        configuration = client.Configuration()
        configuration.host = self.k8s_url
        configuration.verify_ssl = False
        configuration.api_key = {"authorization": "Bearer " + self.get_token()}
        client1 = api_client.ApiClient(configuration=configuration)
        api = core_v1_api.CoreV1Api(client1)
        return api

    def get_namespace_list(self):
        """
        获取命名空间列表
        :return:
        """
        api = self.get_api()
        namespace_list = []
        for ns in api.list_namespace().items:
            # print(ns.metadata.name)
            namespace_list.append(ns.metadata.name)

        return namespace_list

    def get_pod_list(self):
       api = self.get_api()
       print("Listing pods with their IPs:")
       ret = api.list_pod_for_all_namespaces(watch=False)
       for i in ret.items:
           print("%s\t%s\t%s" % (i.status.pod_ip, i.metadata.namespace, i.metadata.name))

    def get_service_list(self):
        api = self.get_api()
        ret = api.list_service_for_all_namespaces(watch=False)
        for i in ret.items:
            print("%s \t%s \t%s \t%s \t%s \n" %(i.kind,i.metadata.namespace,i.metadata.name,i.spec.cluster_ip,i.spec.ports))

if __name__ == '__main__':
    namespace_list = KubernetesTools().get_namespace_list()
    pod_list = KubernetesTools().get_pod_list()
    service = KubernetesTools().get_service_list()
    print(namespace_list)
    print(pod_list)
    print(service)

到此这篇关于Python使用Kubernetes API访问集群的文章就介绍到这了,更多相关Python Kubernetes API访问集群内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
把大数据数字口语化(python与js)两种实现
Feb 21 Python
Python学习笔记整理3之输入输出、python eval函数
Dec 14 Python
python 回调函数和回调方法的实现分析
Mar 23 Python
详解python如何调用C/C++底层库与互相传值
Aug 10 Python
解决Scrapy安装错误:Microsoft Visual C++ 14.0 is required...
Oct 01 Python
基于Python中numpy数组的合并实例讲解
Apr 04 Python
利用Python实现手机短信监控通知的方法
Jul 22 Python
pytorch实现用Resnet提取特征并保存为txt文件的方法
Aug 20 Python
基于pandas中expand的作用详解
Dec 17 Python
keras中的backend.clip用法
May 22 Python
用python监控服务器的cpu,磁盘空间,内存,超过邮件报警
Jan 29 Python
Python文件的操作示例的详细讲解
Apr 08 Python
如何利用pygame实现打飞机小游戏
Python中requests做接口测试的方法
python关于集合的知识案例详解
May 30 #Python
教你漂亮打印Pandas DataFrames和Series
pytorch 实现多个Dataloader同时训练
python 如何做一个识别率百分百的OCR
基于PyTorch实现一个简单的CNN图像分类器
May 29 #Python
You might like
PHP 获取文件权限函数介绍
2013/07/11 PHP
PHP同时连接多个mysql数据库示例代码
2014/03/17 PHP
fckeditor上传文件按日期存放及重命名方法
2015/05/22 PHP
php实现CSV文件导入和导出
2015/10/24 PHP
微信支付扫码支付php版
2016/07/22 PHP
PHP简单遍历对象示例
2016/09/28 PHP
PHP实现的mysql读写分离操作示例
2018/05/22 PHP
JavaScript 异步调用框架 (Part 3 - 代码实现)
2009/08/04 Javascript
键盘上一张下一张兼容IE/google/firefox等浏览器
2014/01/28 Javascript
JavaScript类属性的访问方式详解
2014/02/11 Javascript
SeaJS入门教程系列之使用SeaJS(二)
2014/03/03 Javascript
jquery获取文档高度和窗口高度汇总
2016/01/25 Javascript
Javascript之Number对象介绍
2016/06/07 Javascript
返回函数的JavaScript函数
2016/06/14 Javascript
bootstrapvalidator之API学习教程
2017/06/29 Javascript
jQuery动态操作表单示例【基于table表格】
2018/12/06 jQuery
jQuery+vue.js实现的多选下拉列表功能示例
2019/01/15 jQuery
小程序分享模块超级详解(推荐)
2019/04/10 Javascript
JavaScript中0、空字符串、'0'是true还是false的知识点分享
2019/09/16 Javascript
python实现simhash算法实例
2014/04/25 Python
在Python中处理字符串之isdecimal()方法的使用
2015/05/20 Python
详解Python的Django框架中的模版相关知识
2015/07/15 Python
详解Python中的内建函数,可迭代对象,迭代器
2019/04/29 Python
python实战串口助手_解决8串口多个发送的问题
2019/06/12 Python
基于Python实现ComicReaper漫画自动爬取脚本过程解析
2019/11/11 Python
K最近邻算法(KNN)---sklearn+python实现方式
2020/02/24 Python
巴西男士胡须和头发护理产品商店:Beard
2017/11/13 全球购物
韩国保养品、日本药妆购物网:小三美日
2018/12/30 全球购物
CHARLES & KEITH加拿大官网:新加坡时尚品牌
2020/03/26 全球购物
市场营销专业推荐信
2013/11/03 职场文书
个人函授自我鉴定
2014/03/25 职场文书
校园文明标语
2014/06/13 职场文书
个人批评与自我批评总结
2014/10/17 职场文书
高中教师个人总结
2015/02/10 职场文书
电视新闻稿
2015/07/17 职场文书
酒店厨房管理制度
2015/08/06 职场文书