Python使用Kubernetes API访问集群
作者:落魄运维 时间:2023-09-23 05:35:31
通过将身份认证令牌直接传给 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举例:
目录结构
配置文件两种方式
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)
来源:https://www.cnblogs.com/Dev0ps/p/14825543.html
标签:Python,Kubernetes,API,访问集群
0
投稿
猜你喜欢
python安装mysql的依赖包mysql-python操作
2024-01-20 22:00:54
Python中的列表及其操作方法
2022-05-24 06:19:41
python flask框架快速入门
2021-10-16 22:02:26
django迁移文件migrations的实现
2022-10-27 02:48:44
JavaScript中的私有成员 Javascript教程
2008-12-02 17:57:00
Windows 本地安装 Mysql8.0图文教程
2024-01-15 17:24:05
Python模拟登录和登录跳转的参考示例
2023-07-29 07:09:47
Perl下应当如何连接Access数据库
2008-12-04 13:06:00
Python:format格式化字符串详解
2021-02-11 19:23:58
使用Python的turtle模块画国旗
2021-10-22 12:31:10
Python实现全排列的打印
2021-09-01 04:08:30
mysql myisam优化设置
2010-03-13 16:59:00
Scrapy框架爬取Boss直聘网Python职位信息的源码
2022-06-30 21:02:47
php反序列化之魔术方法超详细讲解
2023-11-16 07:24:59
Tornado 多进程实现分析详解
2022-06-13 20:51:56
Python语言编写电脑时间自动同步小工具
2023-12-23 20:46:08
RHEL下架设MYSQL集群
2008-12-24 16:05:00
用XsltArgumentList实现xsl的参数调用
2008-09-04 11:24:00
Dreamweaver定义本地站点
2010-07-02 16:27:00
ASP防止图片木马上传的代码
2011-02-05 11:08:00