Create vps_monitor.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221import paramikoimport scheduleimport timeimport osimport sysfrom flask import Flask, jsonify, render_template_stringfrom threading import Threadimport 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) # 获取上次保存的 PID(如果有) last_pid = vps_status.get(config['hostname'], {}).get('pid', None) # 检查脚本是否正在运行并获取运行时间和PID if last_pid: check_command = f"ps -p {last_pid} -o pid,etime,args" else: check_command = f"ps -eo pid,etime,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 (last_pid or script_path in output): parts = output.split() pid = last_pid if last_pid else parts[0] runtime = parts[1] if len(parts) > 1 else "Unknown" status = "Running" logger.info(f"Script is running. PID: {pid}, Runtime: {runtime}") 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 & echo $!" stdin, stdout, stderr = client.exec_command(restart_command) new_pid = stdout.read().decode('utf-8').strip() if new_pid.isdigit(): pid = new_pid runtime = "Just started" status = "Restarted" logger.info(f"Script restarted. New PID: {pid}") else: pid = "N/A" runtime = "N/A" status = "Restart Failed" logger.error(f"Failed to restart script") vps_status[config['hostname']] = { 'index': config['index'], 'status': status, 'last_check': time.strftime('%Y-%m-%d %H:%M:%S'), 'username': config['username'], 'runtime': runtime, 'pid': pid } except Exception as e: logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']}: {str(e)}") vps_status[config['hostname']] = { 'index': config['index'], 'status': f"Error: {str(e)}", 'last_check': time.strftime('%Y-%m-%d %H:%M:%S'), 'username': config['username'], 'runtime': "N/A", 'pid': "N/A" } 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 | Runtime | PID |\n" table += "+---------+-----------------------+----------+-------------------------+----------+----------+-------+\n" # 添加每个VPS的状态 for hostname, status in vps_status.items(): table += "| {:<7} | {:<21} | {:<8} | {:<23} | {:<8} | {:<8} | {:<5} |\n".format( status['index'], hostname[:21], status['status'][:8], status['last_check'], status['username'][:8], status['runtime'][:8], status['pid'][:5] ) table += "+---------+-----------------------+----------+-------------------------+----------+----------+-------+\n" logger.info("\n" + table)
@app.route('/')def index(): html = ''' <h1>VPS Status Overview</h1> <table border="1"> <tr> <th>Index</th> <th>Hostname</th> <th>Status</th> <th>Last Check</th> <th>Username</th> <th>Runtime</th> <th>PID</th> </tr> {% for hostname, data in vps_status.items() %} <tr> <td>{{ data.index }}</td> <td><a href="/status/{{ hostname }}">{{ hostname }}</a></td> <td>{{ data.status }}</td> <td>{{ data.last_check }}</td> <td>{{ data.username }}</td> <td>{{ data.runtime }}</td> <td>{{ data.pid }}</td> </tr> {% endfor %} </table> ''' return render_template_string(html, vps_status=vps_status)
@app.route('/status/<hostname>')def vps_status_detail(hostname): if hostname in vps_status: return jsonify(vps_status[hostname]) else: return jsonify({"error": "VPS not found"}), 404
@app.route('/health')def health_check(): return jsonify({"status": "healthy", "uptime": time.time() - start_time}), 200
def run_flask(): app.run(host='0.0.0.0', port=8080)
def main(): global start_time start_time = time.time() logger.info("===== VPS monitoring script is starting =====") flask_thread = Thread(target=run_flask) flask_thread.start() logger.info("Flask server started in background")
vps_configs = get_vps_configs() logger.info(f"Found {len(vps_configs)} VPS configurations")
logger.info("Running initial VPS check") check_all_vps()
schedule.every(15).minutes.do(check_all_vps) logger.info("Scheduled VPS check every 15 minutes") logger.info("===== VPS monitoring script is running =====") heartbeat_count = 0 while True: schedule.run_pending() time.sleep(60) heartbeat_count += 1 if heartbeat_count % 5 == 0: # 每5分钟输出一次心跳信息 logger.info(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
if __name__ == "__main__": main()vps_monitor.pyAdded+221