接近完善的代码,待生产环境测试。

This commit is contained in:
panjunlan
2026-02-21 14:26:14 +08:00
parent 9024e9c8e4
commit 17e9e0c3bc
11 changed files with 357 additions and 293 deletions

63
main.py
View File

@@ -1,20 +1,59 @@
# 这是一个示例 Python 脚本。
# 按 Shift+F10 执行或将其替换为您的代码。
# 按 双击 Shift 在所有地方搜索类、文件、工具窗口、操作和设置。
import time
from apscheduler.schedulers.background import BackgroundScheduler
from utils.logger import logger
from config.settings import YAML_OUTPUT_PATH
from core.get_vm_snapshots import get_all_vms
from core.data_exporter import create_excel_report, export_yaml
from core.remove_snapshots import load_old_snapshots, remove_snapshot
def print_hi(name):
# 在下面的代码行中使用断点来调试脚本。
print(f'Hi, {name}') # 按 Ctrl+F8 切换断点。
def export_files():
"""导出Excel和Yaml文件的函数"""
logger.info("🔍 开始收集VM和快照信息...")
vms = get_all_vms() # 主函数入口,获取虚拟机信息
# 导出Excel报表
logger.info("📝 开始导出Excel报表...")
old_snapshots = create_excel_report(vms) # 生成Excel报告并获取旧快照
# 导出Yaml文件
logger.info("📝 开始导出 Yaml 文件...")
export_yaml(old_snapshots)
logger.info("========== Excel和Yaml文件导出完成 ==========")
# 按装订区域中的绿色按钮以运行脚本。
if __name__ == '__main__':
print_hi('PyCharm')
# 访问 https://www.jetbrains.com/help/pycharm/ 获取 PyCharm 帮助
def delete_old_snapshots():
"""删除旧快照的函数"""
logger.info("🗑️ 开始删除过旧快照...")
old_snapshots = load_old_snapshots(YAML_OUTPUT_PATH)
remove_snapshot(old_snapshots)
logger.info("========== VM快照清理任务执行完成 ==========")
def main():
"""主执行函数"""
# 设置定时任务
scheduler = BackgroundScheduler()
# 每周六凌晨4点导出Excel和Yaml文件
scheduler.add_job(export_files, 'cron', day_of_week='sat', hour=4, minute=0)
# 每周六晚上7点执行删除快照任务
scheduler.add_job(delete_old_snapshots, 'cron', day_of_week='sat', hour=19, minute=0)
scheduler.start()
logger.info("定时任务已设置每周六凌晨4点导出文件晚上7点删除快照")
try:
# 保持主程序运行,以便调度器能正常工作
while True:
time.sleep(1)
except (KeyboardInterrupt, SystemExit):
scheduler.shutdown()
if __name__ == "__main__":
main()