xjf6b commited on
Commit
b613ce1
·
verified ·
1 Parent(s): 7f5ebc7

Update vps_monitor.py

Browse files
Files changed (1) hide show
  1. vps_monitor.py +22 -73
vps_monitor.py CHANGED
@@ -6,15 +6,14 @@ import sys
6
  from flask import Flask, jsonify, render_template_string
7
  from threading import Thread
8
  import logging
9
- from datetime import datetime, timedelta
10
 
11
  app = Flask(__name__)
12
 
13
  vps_status = {}
14
 
15
- # 设置日志
16
  logging.basicConfig(
17
- level=logging.DEBUG, # 将日志级别改为 DEBUG 以获取更多信息
18
  format='%(asctime)s - %(levelname)s - %(message)s',
19
  handlers=[
20
  logging.StreamHandler(sys.stdout),
@@ -44,41 +43,30 @@ def get_vps_configs():
44
  script_index += 1
45
 
46
  for script_path in script_paths:
47
- config = {
48
  'index': index,
49
  'hostname': hostname,
50
  'username': username,
51
  'password': password,
52
  'script_path': script_path
53
- }
54
- configs.append(config)
55
 
56
  index += 1
57
  return configs
58
 
59
  def parse_runtime(etime):
60
- logger.debug(f"Parsing runtime: {etime}")
61
  parts = etime.split('-')
62
- if len(parts) > 1:
63
- days = int(parts[0])
64
- time_parts = parts[1].split(':')
65
- else:
66
- days = 0
67
- time_parts = parts[0].split(':')
68
 
69
  if len(time_parts) == 3:
70
  hours, minutes, seconds = map(int, time_parts)
71
  elif len(time_parts) == 2:
72
- hours, minutes = map(int, time_parts)
73
- seconds = 0
74
  else:
75
- logger.warning(f"Unexpected time format: {etime}")
76
  return "0:00:00"
77
 
78
- total_seconds = days * 86400 + hours * 3600 + minutes * 60 + seconds
79
- runtime = str(timedelta(seconds=total_seconds))
80
- logger.debug(f"Parsed runtime: {runtime}")
81
- return runtime
82
 
83
  def check_and_run_script(config):
84
  logger.info(f"Checking VPS {config['index']}: {config['hostname']} - {config['script_path']}")
@@ -86,57 +74,34 @@ def check_and_run_script(config):
86
  try:
87
  client = paramiko.SSHClient()
88
  client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
89
-
90
- client.connect(
91
- hostname=config['hostname'],
92
- username=config['username'],
93
- password=config['password'],
94
- port=22
95
- )
96
 
97
  script_path = config['script_path']
98
  script_name = os.path.basename(script_path)
99
  key = f"{config['hostname']}:{script_name}"
100
 
101
- # 获取上次保存的 PID(如果有)
102
  last_pid = vps_status.get(key, {}).get('pid', None)
103
-
104
- # 检查进程是否在运行
105
- if last_pid:
106
- check_command = f"ps -p {last_pid} -o pid=,etime=,args="
107
- else:
108
- check_command = f"ps aux | grep '{script_path}' | grep -v grep"
109
 
110
  stdin, stdout, stderr = client.exec_command(check_command)
111
  output = stdout.read().decode('utf-8').strip()
112
- logger.debug(f"Raw output from ps command: {output}")
113
 
114
  if output and (last_pid or script_path in output):
115
  parts = output.split()
116
  if last_pid:
117
- pid = last_pid
118
- runtime = parse_runtime(parts[1]) if len(parts) > 1 else "0:00:00"
119
  else:
120
- pid = parts[1] if len(parts) > 1 else "Unknown"
121
- runtime = parse_runtime(parts[9]) if len(parts) > 9 else "0:00:00"
122
  status = "Running"
123
- logger.info(f"Script {script_name} is running. PID: {pid}, Runtime: {runtime}")
124
  else:
125
  logger.info(f"Script {script_name} not running. Attempting to restart.")
126
- restart_command = f"nohup /bin/sh {script_path} > /dev/null 2>&1 & echo $!"
127
- stdin, stdout, stderr = client.exec_command(restart_command)
128
  new_pid = stdout.read().decode('utf-8').strip()
129
 
130
  if new_pid.isdigit():
131
- pid = new_pid
132
- runtime = "0:00:00"
133
- status = "Restarted"
134
- logger.info(f"Script {script_name} restarted. New PID: {pid}")
135
  else:
136
- pid = "N/A"
137
- runtime = "N/A"
138
- status = "Restart Failed"
139
- logger.error(f"Failed to restart script {script_name}")
140
 
141
  vps_status[key] = {
142
  'index': config['index'],
@@ -150,8 +115,7 @@ def check_and_run_script(config):
150
 
151
  except Exception as e:
152
  logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']} - {script_name}: {str(e)}")
153
- key = f"{config['hostname']}:{script_name}"
154
- vps_status[key] = {
155
  'index': config['index'],
156
  'status': f"Error: {str(e)}",
157
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
@@ -166,27 +130,18 @@ def check_and_run_script(config):
166
 
167
  def check_all_vps():
168
  logger.info("Starting VPS check")
169
- vps_configs = get_vps_configs()
170
- for config in vps_configs:
171
  check_and_run_script(config)
172
 
173
- # 创建表格头
174
  table = "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
175
  table += "| Index | Hostname | Script Name | Status | Last Check | Username | Runtime | PID |\n"
176
  table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
177
 
178
- # 添加每个VPS的状态
179
  for key, status in vps_status.items():
180
  hostname, script_name = key.split(':')
181
  table += "| {:<7} | {:<21} | {:<16} | {:<8} | {:<23} | {:<8} | {:<8} | {:<5} |\n".format(
182
- status['index'],
183
- hostname[:21],
184
- script_name[:16],
185
- status['status'][:8],
186
- status['last_check'],
187
- status['username'][:8],
188
- status['runtime'],
189
- status['pid'][:5]
190
  )
191
  table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
192
 
@@ -225,10 +180,7 @@ def index():
225
 
226
  @app.route('/status/<path:key>')
227
  def vps_status_detail(key):
228
- if key in vps_status:
229
- return jsonify(vps_status[key])
230
- else:
231
- return jsonify({"error": "VPS or script not found"}), 404
232
 
233
  @app.route('/health')
234
  def health_check():
@@ -243,13 +195,10 @@ def main():
243
 
244
  logger.info("===== VPS monitoring script is starting =====")
245
 
246
- flask_thread = Thread(target=run_flask)
247
- flask_thread.start()
248
  logger.info("Flask server started in background")
249
 
250
- logger.info("Running initial VPS check")
251
  check_all_vps()
252
-
253
  schedule.every(15).minutes.do(check_all_vps)
254
  logger.info("Scheduled VPS check every 15 minutes")
255
 
@@ -260,7 +209,7 @@ def main():
260
  schedule.run_pending()
261
  time.sleep(60)
262
  heartbeat_count += 1
263
- if heartbeat_count % 5 == 0: # 每5分钟输出一次心跳信息
264
  logger.info(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
265
 
266
  if __name__ == "__main__":
 
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',
18
  handlers=[
19
  logging.StreamHandler(sys.stdout),
 
43
  script_index += 1
44
 
45
  for script_path in script_paths:
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']} - {config['script_path']}")
 
74
  try:
75
  client = paramiko.SSHClient()
76
  client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
77
+ client.connect(hostname=config['hostname'], username=config['username'], password=config['password'], port=22)
 
 
 
 
 
 
78
 
79
  script_path = config['script_path']
80
  script_name = os.path.basename(script_path)
81
  key = f"{config['hostname']}:{script_name}"
82
 
 
83
  last_pid = vps_status.get(key, {}).get('pid', None)
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 (last_pid or script_path in output):
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 {script_name} not running. Attempting to restart.")
98
+ stdin, stdout, stderr = client.exec_command(f"nohup /bin/sh {script_path} > /dev/null 2>&1 & echo $!")
 
99
  new_pid = stdout.read().decode('utf-8').strip()
100
 
101
  if new_pid.isdigit():
102
+ pid, runtime, status = new_pid, "0:00:00", "Restarted"
 
 
 
103
  else:
104
+ pid, runtime, status = "N/A", "N/A", "Restart Failed"
 
 
 
105
 
106
  vps_status[key] = {
107
  'index': config['index'],
 
115
 
116
  except Exception as e:
117
  logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']} - {script_name}: {str(e)}")
118
+ vps_status[f"{config['hostname']}:{script_name}"] = {
 
119
  'index': config['index'],
120
  'status': f"Error: {str(e)}",
121
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
 
130
 
131
  def check_all_vps():
132
  logger.info("Starting VPS check")
133
+ for config in get_vps_configs():
 
134
  check_and_run_script(config)
135
 
 
136
  table = "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
137
  table += "| Index | Hostname | Script Name | Status | Last Check | Username | Runtime | PID |\n"
138
  table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
139
 
 
140
  for key, status in vps_status.items():
141
  hostname, script_name = key.split(':')
142
  table += "| {:<7} | {:<21} | {:<16} | {:<8} | {:<23} | {:<8} | {:<8} | {:<5} |\n".format(
143
+ status['index'], hostname[:21], script_name[:16], status['status'][:8],
144
+ status['last_check'], status['username'][:8], status['runtime'], status['pid'][:5]
 
 
 
 
 
 
145
  )
146
  table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
147
 
 
180
 
181
  @app.route('/status/<path:key>')
182
  def vps_status_detail(key):
183
+ return jsonify(vps_status[key]) if key in vps_status else (jsonify({"error": "VPS or script not found"}), 404)
 
 
 
184
 
185
  @app.route('/health')
186
  def health_check():
 
195
 
196
  logger.info("===== VPS monitoring script is starting =====")
197
 
198
+ Thread(target=run_flask).start()
 
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
  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__":