需求:
公司内有若干k8s集群,需要每周统计集群的基本信息,因为很多集群不方便纳管,所以只能手动统计。
因此先在每台集群的管理节点部署资源统计脚本,此处脚本忽略,根据需要定制即可,输出的样例数据如下,每个主机返回9个数据:
测试集群1
1333145612561257
1123M
123M
1245不必关心数字数字代表什么,只需要从上大小把你的数据排列好就行。
python脚本,找一台主机执行如下脚本,脚本中定义了你的所有集群的管理节点的ip。
#!/usr/bin/python3
import subprocess
import openpyxl
import time
# 定义远程命令
command = "cat /root/node_info"
# 定义远程主机列表
hosts = ["ip1", "ip2", "ip3"]
# 获取当前时间戳
timestamp = time.strftime("%Y%m%d%H%M%S", time.localtime())
# 创建 Excel 文件
workbook = openpyxl.Workbook()
worksheet = workbook.active
# 定义 Excel 列名,此处增加了2列存储额外的集群ip和状态数据
worksheet.append(['集群ip', '执行状态', '列1','列2', '列3', '列4', '列5', '列6', '列7', '列8', '列9'])
# 执行远程命令并将结果保存到 Excel 文件中
for host in hosts:
process = subprocess.Popen(["ansible", host, "-m", "shell", "-a", command], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
if process.returncode == 0:
output = stdout.decode().strip().split('\n')
row = [host] + output
else:
row = [host, '失败', stderr.decode().strip()]
worksheet.append(row)
# 保存 Excel 文件
filename = f"k8s_report_{timestamp}.xlsx"
workbook.save(filename)
生成excel结果:

评论