Spaces:
Sleeping
Sleeping
Update vps_monitor.py
Browse files- vps_monitor.py +62 -86
vps_monitor.py
CHANGED
@@ -6,12 +6,12 @@ import sys
|
|
6 |
from flask import Flask, jsonify, render_template_string
|
7 |
from threading import Thread
|
8 |
import logging
|
9 |
-
from datetime import timedelta
|
10 |
|
11 |
app = Flask(__name__)
|
12 |
|
13 |
vps_status = {}
|
14 |
|
|
|
15 |
logging.basicConfig(
|
16 |
level=logging.INFO,
|
17 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
@@ -30,99 +30,67 @@ def get_vps_configs():
|
|
30 |
if not hostname:
|
31 |
break
|
32 |
|
33 |
-
|
34 |
-
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
-
break
|
42 |
-
script_paths.append(script_path.strip())
|
43 |
-
script_index += 1
|
44 |
|
45 |
-
|
46 |
-
configs.append({
|
47 |
-
'index': index,
|
48 |
-
'hostname': hostname,
|
49 |
-
'username': username,
|
50 |
-
'password': password,
|
51 |
-
'script_path': script_path
|
52 |
-
})
|
53 |
|
54 |
index += 1
|
55 |
return configs
|
56 |
|
57 |
-
def parse_runtime(etime):
|
58 |
-
parts = etime.split('-')
|
59 |
-
days = int(parts[0]) if len(parts) > 1 else 0
|
60 |
-
time_parts = parts[-1].split(':')
|
61 |
-
|
62 |
-
if len(time_parts) == 3:
|
63 |
-
hours, minutes, seconds = map(int, time_parts)
|
64 |
-
elif len(time_parts) == 2:
|
65 |
-
hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), 0
|
66 |
-
else:
|
67 |
-
return "0:00:00"
|
68 |
-
|
69 |
-
return str(timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds))
|
70 |
-
|
71 |
def check_and_run_script(config):
|
72 |
-
logger.info(f"Checking VPS {config['index']}: {config['hostname']}
|
73 |
client = None
|
74 |
try:
|
75 |
client = paramiko.SSHClient()
|
76 |
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
78 |
|
79 |
script_path = config['script_path']
|
80 |
script_name = os.path.basename(script_path)
|
81 |
-
key = f"{config['hostname']}:{script_name}"
|
82 |
|
83 |
-
|
84 |
-
check_command = f"ps -p {last_pid} -o pid=,etime=,args=" if last_pid else f"ps aux | grep '{script_path}' | grep -v grep"
|
85 |
|
86 |
stdin, stdout, stderr = client.exec_command(check_command)
|
87 |
output = stdout.read().decode('utf-8').strip()
|
88 |
|
89 |
-
if output and
|
90 |
-
parts = output.split()
|
91 |
-
if last_pid:
|
92 |
-
pid, runtime = last_pid, parse_runtime(parts[1]) if len(parts) > 1 else "0:00:00"
|
93 |
-
else:
|
94 |
-
pid, runtime = parts[1] if len(parts) > 1 else "Unknown", parse_runtime(parts[9]) if len(parts) > 9 else "0:00:00"
|
95 |
status = "Running"
|
|
|
96 |
else:
|
97 |
-
logger.info(f"Script
|
98 |
-
|
99 |
-
|
100 |
|
101 |
-
|
102 |
-
|
103 |
-
else:
|
104 |
-
pid, runtime, status = "N/A", "N/A", "Restart Failed"
|
105 |
|
106 |
-
vps_status[
|
107 |
'index': config['index'],
|
108 |
'status': status,
|
109 |
'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
|
110 |
-
'username': config['username']
|
111 |
-
'script_name': script_name,
|
112 |
-
'runtime': runtime,
|
113 |
-
'pid': pid
|
114 |
}
|
115 |
|
116 |
except Exception as e:
|
117 |
-
logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']}
|
118 |
-
vps_status[
|
119 |
'index': config['index'],
|
120 |
'status': f"Error: {str(e)}",
|
121 |
'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
|
122 |
-
'username': config['username']
|
123 |
-
'script_name': script_name,
|
124 |
-
'runtime': "N/A",
|
125 |
-
'pid': "N/A"
|
126 |
}
|
127 |
finally:
|
128 |
if client:
|
@@ -130,20 +98,25 @@ def check_and_run_script(config):
|
|
130 |
|
131 |
def check_all_vps():
|
132 |
logger.info("Starting VPS check")
|
133 |
-
|
|
|
134 |
check_and_run_script(config)
|
135 |
|
136 |
-
|
137 |
-
table
|
138 |
-
table += "
|
|
|
139 |
|
140 |
-
|
141 |
-
|
142 |
-
table += "| {:<7} | {:<21} | {:<
|
143 |
-
status['index'],
|
144 |
-
|
|
|
|
|
|
|
145 |
)
|
146 |
-
table += "
|
147 |
|
148 |
logger.info("\n" + table)
|
149 |
|
@@ -155,32 +128,29 @@ def index():
|
|
155 |
<tr>
|
156 |
<th>Index</th>
|
157 |
<th>Hostname</th>
|
158 |
-
<th>Script Name</th>
|
159 |
<th>Status</th>
|
160 |
<th>Last Check</th>
|
161 |
<th>Username</th>
|
162 |
-
<th>Runtime</th>
|
163 |
-
<th>PID</th>
|
164 |
</tr>
|
165 |
-
{% for
|
166 |
<tr>
|
167 |
<td>{{ data.index }}</td>
|
168 |
-
<td><a href="/status/{{
|
169 |
-
<td>{{ data.script_name }}</td>
|
170 |
<td>{{ data.status }}</td>
|
171 |
<td>{{ data.last_check }}</td>
|
172 |
<td>{{ data.username }}</td>
|
173 |
-
<td>{{ data.runtime }}</td>
|
174 |
-
<td>{{ data.pid }}</td>
|
175 |
</tr>
|
176 |
{% endfor %}
|
177 |
</table>
|
178 |
'''
|
179 |
return render_template_string(html, vps_status=vps_status)
|
180 |
|
181 |
-
@app.route('/status/<
|
182 |
-
def vps_status_detail(
|
183 |
-
|
|
|
|
|
|
|
184 |
|
185 |
@app.route('/health')
|
186 |
def health_check():
|
@@ -195,10 +165,16 @@ def main():
|
|
195 |
|
196 |
logger.info("===== VPS monitoring script is starting =====")
|
197 |
|
198 |
-
Thread(target=run_flask)
|
|
|
199 |
logger.info("Flask server started in background")
|
200 |
|
|
|
|
|
|
|
|
|
201 |
check_all_vps()
|
|
|
202 |
schedule.every(15).minutes.do(check_all_vps)
|
203 |
logger.info("Scheduled VPS check every 15 minutes")
|
204 |
|
@@ -209,7 +185,7 @@ def main():
|
|
209 |
schedule.run_pending()
|
210 |
time.sleep(60)
|
211 |
heartbeat_count += 1
|
212 |
-
if heartbeat_count % 5 == 0:
|
213 |
logger.info(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
|
214 |
|
215 |
if __name__ == "__main__":
|
|
|
6 |
from flask import Flask, jsonify, render_template_string
|
7 |
from threading import Thread
|
8 |
import logging
|
|
|
9 |
|
10 |
app = Flask(__name__)
|
11 |
|
12 |
vps_status = {}
|
13 |
|
14 |
+
# 设置日志
|
15 |
logging.basicConfig(
|
16 |
level=logging.INFO,
|
17 |
format='%(asctime)s - %(levelname)s - %(message)s',
|
|
|
30 |
if not hostname:
|
31 |
break
|
32 |
|
33 |
+
config = {
|
34 |
+
'index': index,
|
35 |
+
'hostname': hostname,
|
36 |
+
'username': os.environ.get(f'USERNAME_{index}'),
|
37 |
+
'password': os.environ.get(f'PASSWORD_{index}'),
|
38 |
+
'script_path': os.environ.get(f'SCRIPT_PATH_{index}')
|
39 |
+
}
|
40 |
+
configs.append(config)
|
|
|
|
|
|
|
41 |
|
42 |
+
logger.info(f"Config {index}: {config['hostname']}, {config['username']}, {config['script_path']}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
43 |
|
44 |
index += 1
|
45 |
return configs
|
46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
47 |
def check_and_run_script(config):
|
48 |
+
logger.info(f"Checking VPS {config['index']}: {config['hostname']}")
|
49 |
client = None
|
50 |
try:
|
51 |
client = paramiko.SSHClient()
|
52 |
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
53 |
+
|
54 |
+
client.connect(
|
55 |
+
hostname=config['hostname'],
|
56 |
+
username=config['username'],
|
57 |
+
password=config['password'],
|
58 |
+
port=22
|
59 |
+
)
|
60 |
|
61 |
script_path = config['script_path']
|
62 |
script_name = os.path.basename(script_path)
|
|
|
63 |
|
64 |
+
check_command = f"ps -eo args | grep {script_name} | grep -v grep"
|
|
|
65 |
|
66 |
stdin, stdout, stderr = client.exec_command(check_command)
|
67 |
output = stdout.read().decode('utf-8').strip()
|
68 |
|
69 |
+
if output and script_path in output:
|
|
|
|
|
|
|
|
|
|
|
70 |
status = "Running"
|
71 |
+
logger.info(f"Script is running on {config['hostname']}")
|
72 |
else:
|
73 |
+
logger.info(f"Script not running on {config['hostname']}. Executing restart script.")
|
74 |
+
restart_command = f"nohup /bin/sh {script_path} > /dev/null 2>&1 &"
|
75 |
+
stdin, stdout, stderr = client.exec_command(restart_command)
|
76 |
|
77 |
+
status = "Restarted"
|
78 |
+
logger.info(f"Script restarted on {config['hostname']}")
|
|
|
|
|
79 |
|
80 |
+
vps_status[config['hostname']] = {
|
81 |
'index': config['index'],
|
82 |
'status': status,
|
83 |
'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
|
84 |
+
'username': config['username']
|
|
|
|
|
|
|
85 |
}
|
86 |
|
87 |
except Exception as e:
|
88 |
+
logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']}: {str(e)}")
|
89 |
+
vps_status[config['hostname']] = {
|
90 |
'index': config['index'],
|
91 |
'status': f"Error: {str(e)}",
|
92 |
'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
|
93 |
+
'username': config['username']
|
|
|
|
|
|
|
94 |
}
|
95 |
finally:
|
96 |
if client:
|
|
|
98 |
|
99 |
def check_all_vps():
|
100 |
logger.info("Starting VPS check")
|
101 |
+
vps_configs = get_vps_configs()
|
102 |
+
for config in vps_configs:
|
103 |
check_and_run_script(config)
|
104 |
|
105 |
+
# 创建表格头
|
106 |
+
table = "+---------+-----------------------+----------+-------------------------+----------+\n"
|
107 |
+
table += "| Index | Hostname | Status | Last Check | Username |\n"
|
108 |
+
table += "+---------+-----------------------+----------+-------------------------+----------+\n"
|
109 |
|
110 |
+
# 添加每个VPS的状态
|
111 |
+
for hostname, status in vps_status.items():
|
112 |
+
table += "| {:<7} | {:<21} | {:<8} | {:<23} | {:<8} |\n".format(
|
113 |
+
status['index'],
|
114 |
+
hostname[:21],
|
115 |
+
status['status'][:8],
|
116 |
+
status['last_check'],
|
117 |
+
status['username'][:8]
|
118 |
)
|
119 |
+
table += "+---------+-----------------------+----------+-------------------------+----------+\n"
|
120 |
|
121 |
logger.info("\n" + table)
|
122 |
|
|
|
128 |
<tr>
|
129 |
<th>Index</th>
|
130 |
<th>Hostname</th>
|
|
|
131 |
<th>Status</th>
|
132 |
<th>Last Check</th>
|
133 |
<th>Username</th>
|
|
|
|
|
134 |
</tr>
|
135 |
+
{% for hostname, data in vps_status.items() %}
|
136 |
<tr>
|
137 |
<td>{{ data.index }}</td>
|
138 |
+
<td><a href="/status/{{ hostname }}">{{ hostname }}</a></td>
|
|
|
139 |
<td>{{ data.status }}</td>
|
140 |
<td>{{ data.last_check }}</td>
|
141 |
<td>{{ data.username }}</td>
|
|
|
|
|
142 |
</tr>
|
143 |
{% endfor %}
|
144 |
</table>
|
145 |
'''
|
146 |
return render_template_string(html, vps_status=vps_status)
|
147 |
|
148 |
+
@app.route('/status/<hostname>')
|
149 |
+
def vps_status_detail(hostname):
|
150 |
+
if hostname in vps_status:
|
151 |
+
return jsonify(vps_status[hostname])
|
152 |
+
else:
|
153 |
+
return jsonify({"error": "VPS not found"}), 404
|
154 |
|
155 |
@app.route('/health')
|
156 |
def health_check():
|
|
|
165 |
|
166 |
logger.info("===== VPS monitoring script is starting =====")
|
167 |
|
168 |
+
flask_thread = Thread(target=run_flask)
|
169 |
+
flask_thread.start()
|
170 |
logger.info("Flask server started in background")
|
171 |
|
172 |
+
vps_configs = get_vps_configs()
|
173 |
+
logger.info(f"Found {len(vps_configs)} VPS configurations")
|
174 |
+
|
175 |
+
logger.info("Running initial VPS check")
|
176 |
check_all_vps()
|
177 |
+
|
178 |
schedule.every(15).minutes.do(check_all_vps)
|
179 |
logger.info("Scheduled VPS check every 15 minutes")
|
180 |
|
|
|
185 |
schedule.run_pending()
|
186 |
time.sleep(60)
|
187 |
heartbeat_count += 1
|
188 |
+
if heartbeat_count % 5 == 0: # 每5分钟输出一次心跳信息
|
189 |
logger.info(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
|
190 |
|
191 |
if __name__ == "__main__":
|