#!/usr/bin/env python3 import re import json import time from datetime import datetime from pathlib import Path # 服务图标映射 SERVICE_ICONS = { 'longhorn': '💾', 'grafana': '📊', 'prometheus': '📈', 'alertmanager': '🔔', 's3': '🗄️', 'console': '🎛️', 'minio': '🗄️', 'dh': '🏠', 'test': '🧪', 'default': '🌐' } # 服务描述映射 SERVICE_DESCRIPTIONS = { 'longhorn': '分布式块存储管理', 'grafana': '监控数据可视化', 'prometheus': '指标监控系统', 'alertmanager': '告警管理系统', 's3': '对象存储 API', 'console': 'MinIO 管理控制台', 'minio': 'MinIO 对象存储', 'dh': '服务导航页面', 'test': '测试服务', 'default': 'K3s 服务' } def parse_caddyfile(caddyfile_path): """解析 Caddyfile 并提取域名""" services = [] try: with open(caddyfile_path, 'r', encoding='utf-8') as f: content = f.read() # 匹配域名配置块 (domain.com {) pattern = r'([a-zA-Z0-9.-]+\.u6\.net3w\.com)\s*\{' matches = re.findall(pattern, content) for domain in matches: # 提取子域名前缀 subdomain = domain.split('.')[0] # 获取图标和描述 icon = SERVICE_ICONS.get(subdomain, SERVICE_ICONS['default']) description = SERVICE_DESCRIPTIONS.get(subdomain, SERVICE_DESCRIPTIONS['default']) # 生成服务名称 name = subdomain.capitalize() if subdomain == 's3': name = 'MinIO S3' elif subdomain == 'console': name = 'MinIO Console' elif subdomain == 'dh': name = '导航页面' services.append({ 'name': name, 'icon': icon, 'url': f'https://{domain}', 'description': description }) # 排序:导航页面放最后 services.sort(key=lambda x: (x['name'] == '导航页面', x['name'])) except Exception as e: print(f"Error parsing Caddyfile: {e}") return services def generate_html(services): """生成 HTML 页面""" services_html = '\n'.join([ f'''
{service['icon']}
{service['name']}
{service['url']}
{service['description']}
''' for service in services ]) html_template = f''' K3s 服务导航

🚀 K3s 服务导航

快速访问您的所有服务

{services_html}
''' return html_template def main(): caddyfile_path = '/etc/caddy/Caddyfile' output_path = '/usr/share/nginx/html/index.html' print(f"Navigation page generator started at {datetime.now()}") print(f"Caddyfile path: {caddyfile_path}") print(f"Output path: {output_path}") while True: try: # 解析 Caddyfile services = parse_caddyfile(caddyfile_path) print(f"Found {len(services)} services") # 生成 HTML html = generate_html(services) # 写入文件 Path(output_path).parent.mkdir(parents=True, exist_ok=True) with open(output_path, 'w', encoding='utf-8') as f: f.write(html) print(f"Updated navigation page at {datetime.now()}") except Exception as e: print(f"Error: {e}") # 每 5 分钟更新一次 time.sleep(300) if __name__ == '__main__': main()