xjf6b commited on
Commit
db2fa40
·
verified ·
1 Parent(s): 3cb838b

Update vps_monitor.py

Browse files
Files changed (1) hide show
  1. vps_monitor.py +12 -41
vps_monitor.py CHANGED
@@ -6,7 +6,6 @@ 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
 
@@ -54,20 +53,6 @@ def get_vps_configs():
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']}")
73
  client = None
@@ -80,18 +65,12 @@ def check_and_run_script(config):
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.")
@@ -99,18 +78,16 @@ def check_and_run_script(config):
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'],
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:
@@ -120,9 +97,7 @@ def check_and_run_script(config):
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:
@@ -133,17 +108,17 @@ def check_all_vps():
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
 
148
  logger.info("\n" + table)
149
 
@@ -159,8 +134,6 @@ def index():
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 key, data in vps_status.items() %}
166
  <tr>
@@ -170,8 +143,6 @@ def index():
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>
 
6
  from flask import Flask, jsonify, render_template_string
7
  from threading import Thread
8
  import logging
 
9
 
10
  app = Flask(__name__)
11
 
 
53
  index += 1
54
  return configs
55
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  def check_and_run_script(config):
57
  logger.info(f"Checking VPS {config['index']}: {config['hostname']} - {config['script_path']}")
58
  client = None
 
65
  script_name = os.path.basename(script_path)
66
  key = f"{config['hostname']}:{script_name}"
67
 
68
+ check_command = f"ps aux | grep '{script_path}' | grep -v grep"
 
69
 
70
  stdin, stdout, stderr = client.exec_command(check_command)
71
  output = stdout.read().decode('utf-8').strip()
72
 
73
+ if output and script_path in output:
 
 
 
 
 
74
  status = "Running"
75
  else:
76
  logger.info(f"Script {script_name} not running. Attempting to restart.")
 
78
  new_pid = stdout.read().decode('utf-8').strip()
79
 
80
  if new_pid.isdigit():
81
+ status = "Restarted"
82
  else:
83
+ status = "Restart Failed"
84
 
85
  vps_status[key] = {
86
  'index': config['index'],
87
  'status': status,
88
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
89
  'username': config['username'],
90
+ 'script_name': script_name
 
 
91
  }
92
 
93
  except Exception as e:
 
97
  'status': f"Error: {str(e)}",
98
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
99
  'username': config['username'],
100
+ 'script_name': script_name
 
 
101
  }
102
  finally:
103
  if client:
 
108
  for config in get_vps_configs():
109
  check_and_run_script(config)
110
 
111
+ table = "+---------+-----------------------+------------------+----------+-------------------------+----------+\n"
112
+ table += "| Index | Hostname | Script Name | Status | Last Check | Username |\n"
113
+ table += "+---------+-----------------------+------------------+----------+-------------------------+----------+\n"
114
 
115
  for key, status in vps_status.items():
116
  hostname, script_name = key.split(':')
117
+ table += "| {:<7} | {:<21} | {:<16} | {:<8} | {:<23} | {:<8} |\n".format(
118
  status['index'], hostname[:21], script_name[:16], status['status'][:8],
119
+ status['last_check'], status['username'][:8]
120
  )
121
+ table += "+---------+-----------------------+------------------+----------+-------------------------+----------+\n"
122
 
123
  logger.info("\n" + table)
124
 
 
134
  <th>Status</th>
135
  <th>Last Check</th>
136
  <th>Username</th>
 
 
137
  </tr>
138
  {% for key, data in vps_status.items() %}
139
  <tr>
 
143
  <td>{{ data.status }}</td>
144
  <td>{{ data.last_check }}</td>
145
  <td>{{ data.username }}</td>
 
 
146
  </tr>
147
  {% endfor %}
148
  </table>