1 kubeconfig文件认证
CMD>conda activate python36
CMD>pip install kubernetes
首先引入SDK支持库。然后将 ~/.kube 的config文件的内容复制到本地目录,保存为文件kubeconfig.yaml,然后运行下面的python代码。
#cp /root/.kube/config /root/kubeconfig.yaml
将代码置于工程目录下。
2 API使用
2.1 列出资源信息
2.1.1 列出namespaces
#encoding:utf8
from kubernetes import client, config
config.kube_config.load_kube_config(config_file = "kubeconfig.yaml")
#获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()
#列出 namespaces
for ns in v1.list_namespace().items:
print(ns.metadata.name)
admin
auth
cert-manager
default
istio-system
knative-serving
kube-node-lease
kube-public
kube-system
kubeflow
local-path-storage
2.1.2 列出services
#encoding:utf8
from kubernetes import client, config
config.kube_config.load_kube_config(config_file = "kubeconfig.yaml")
#获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()
# 列出所有的services
res = v1.list_service_for_all_namespaces(watch=False)
i = 0
for re in res.items:
print(i,re.kind, re.metadata.namespace, re.metadata.name, re.spec.cluster_ip, re.spec.ports)
i = i+1
0 None admin me 10.110.40.152 [{‘name’: ‘http-me’,
‘node_port’: None,
‘port’: 80,
‘protocol’: ‘TCP’,
‘target_port’: 8888}]
1 None auth dex 10.101.7.135 [{‘name’: ‘dex’,
‘node_port’: 32000,
‘port’: 5556,
‘protocol’: ‘TCP’,
‘target_port’: 5556}]
2.1.3 列出pod
#encoding:utf8
from kubernetes import client, config
config.kube_config.load_kube_config(config_file = "kubeconfig.yaml")
#获取API的CoreV1Api版本对象
v1 = client.CoreV1Api()
# 列出所有的pod
res = v1.list_pod_for_all_namespaces(watch=False)
i = 0
for re in res.items:
print(i, re.status.pod_ip, re.metadata.namespace, re.metadata.name)
i = i+1
0 10.244.1.33 admin me-0
1 10.244.1.248 auth dex-d468d6b64-lbphz
2 10.244.1.27 cert-manager cert-manager-5d849b9888-wt5zk