Commit d4baeafb authored by jinkaiqiang's avatar jinkaiqiang

k8s删除pod脚本

parent 6c5c930e
# -*- coding:utf-8 -*-
'''
k8s delete po命令(用于重启)
'''
import os
import sys, getopt
help_txt = '''
k8s delete po命令(用于重启)
delete_pod.py -p <pod> -n <namespace>
-p --pod 应用名字
-n --namespace 命名空间
'''
class K8STool:
def delete_pod(self, pod, namespaces):
if not pod:
print('pod 不能为空')
print(help_txt)
sys.exit(2)
if not namespaces:
self._delete_pod(pod)
else:
for namespace in namespaces.split(','):
self.change_namespace(namespace)
self._delete_pod(pod)
def _delete_pod(self, pod):
print("正在删除{}".format(pod))
with os.popen("kubectl get po |grep {}".format(pod) + "| awk '{print $1}' |xargs kubectl delete po") as f:
cmd_txt = f.read()
print(cmd_txt)
if 'Error from server' in cmd_txt:
print('删除pod{}失败,错误:{}'.format(pod, cmd_txt))
sys.exit(2)
def change_namespace(self, namespace):
with os.popen('kubens {}'.format(namespace)) as f:
cmd_txt = f.read()
print(cmd_txt)
if 'error' in cmd_txt:
print('namespace切换错误:{}'.format(cmd_txt))
sys.exit(2)
def main(argv):
pod = ''
namespaces = ''
try:
# args: 要解析的命令行参数列表。
# options : 以字符串的格式定义,options 后的冒号 : 表示如果设置该选项,必须有附加的参数,否则就不附加参数。
# long_options : 以列表的格式定义,long_options 后的等号 = 表示该选项必须有附加的参数,不带冒号表示该选项不附加参数。
opts, args = getopt.getopt(argv, "hp:n:", ["pod=", "namespace="])
except getopt.GetoptError:
print(help_txt)
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print(help_txt)
sys.exit()
elif opt in ("-p", "--pod"):
pod = arg
elif opt in ("-n", "--namespace"):
namespaces = arg
K8STool().delete_pod(pod, namespaces)
if __name__ == '__main__':
main(sys.argv[1:])
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment