import paramiko import schedule import time import os import sys from flask import Flask, jsonify, render_template_string from threading import Thread import logging app = Flask(__name__) vps_status = {} # 设置日志 logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s', handlers=[ logging.StreamHandler(sys.stdout), logging.StreamHandler(sys.stderr) ] ) logger = logging.getLogger() def get_vps_configs(): configs = [] index = 1 while True: hostname = os.environ.get(f'HOSTNAME_{index}') if not hostname: break config = { 'index': index, 'hostname': hostname, 'username': os.environ.get(f'USERNAME_{index}'), 'password': os.environ.get(f'PASSWORD_{index}'), 'script_path': os.environ.get(f'SCRIPT_PATH_{index}') } configs.append(config) logger.info(f"Config {index}: {config['hostname']}, {config['username']}, {config['script_path']}") index += 1 return configs def check_and_run_script(config): logger.info(f"Checking VPS {config['index']}: {config['hostname']}") client = None try: client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect( hostname=config['hostname'], username=config['username'], password=config['password'], port=22 ) script_path = config['script_path'] script_name = os.path.basename(script_path) check_command = f"ps -eo args | grep {script_name} | grep -v grep" stdin, stdout, stderr = client.exec_command(check_command) output = stdout.read().decode('utf-8').strip() if output and script_path in output: status = "Running" logger.info(f"Script is running on {config['hostname']}") else: logger.info(f"Script not running on {config['hostname']}. Executing restart script.") restart_command = f"nohup /bin/sh {script_path} > /dev/null 2>&1 &" stdin, stdout, stderr = client.exec_command(restart_command) status = "Restarted" logger.info(f"Script restarted on {config['hostname']}") vps_status[config['index']] = { 'index': config['index'], 'hostname': config['hostname'], 'status': status, 'last_check': time.strftime('%Y-%m-%d %H:%M:%S'), 'username': config['username'] } except Exception as e: logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']}: {str(e)}") vps_status[config['index']] = { 'index': config['index'], 'hostname': config['hostname'], 'status': f"Error: {str(e)}", 'last_check': time.strftime('%Y-%m-%d %H:%M:%S'), 'username': config['username'] } finally: if client: client.close() def check_all_vps(): logger.info("Starting VPS check") vps_configs = get_vps_configs() for config in vps_configs: check_and_run_script(config) # 创建表格头 table = "+---------+-----------------------+----------+-------------------------+----------+\n" table += "| Index | Hostname | Status | Last Check | Username |\n" table += "+---------+-----------------------+----------+-------------------------+----------+\n" # 添加每个VPS的状态 for index in sorted(vps_status.keys()): status = vps_status[index] table += "| {:<7} | {:<21} | {:<8} | {:<23} | {:<8} |\n".format( status['index'], status['hostname'][:21], status['status'][:8], status['last_check'], status['username'][:8] ) table += "+---------+-----------------------+----------+-------------------------+----------+\n" logger.info("\n" + table) @app.route('/') def index(): html = '''
Index | Hostname | Status | Last Check | Username |
---|---|---|---|---|
{{ data['index'] }} | {{ data['hostname'] }} | {{ data['status'] }} | {{ data['last_check'] }} | {{ data['username'] }} |