xjf6b commited on
Commit
1dba9ff
·
verified ·
1 Parent(s): d732277

Update vps_monitor.py

Browse files
Files changed (1) hide show
  1. vps_monitor.py +41 -22
vps_monitor.py CHANGED
@@ -72,40 +72,55 @@ def check_and_run_script(config):
72
 
73
  script_path = config['script_path']
74
  script_name = os.path.basename(script_path)
 
 
 
 
 
 
 
 
 
 
75
 
76
- check_command = f"ps -eo pid,etime,args | grep {script_name} | grep -v grep"
77
  stdin, stdout, stderr = client.exec_command(check_command)
78
  output = stdout.read().decode('utf-8').strip()
79
 
80
- if output:
81
- status = "Running"
82
- # 解析运行时间
83
  parts = output.split()
84
- if len(parts) > 1:
85
- runtime = parts[1]
 
86
  else:
87
- runtime = "Unknown"
 
 
 
88
  else:
89
- restart_command = f"/bin/sh {script_path}"
 
90
  stdin, stdout, stderr = client.exec_command(restart_command)
91
- exit_status = stdout.channel.recv_exit_status()
92
 
93
- if exit_status == 0:
94
- status = "Restarted"
95
  runtime = "Just started"
 
 
96
  else:
97
- error_output = stderr.read().decode('utf-8')
98
- status = f"Error: {error_output}"
99
  runtime = "N/A"
 
 
100
 
101
- key = f"{config['hostname']}:{script_name}"
102
  vps_status[key] = {
103
  'index': config['index'],
104
  'status': status,
105
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
106
  'username': config['username'],
107
  'script_name': script_name,
108
- 'runtime': runtime
 
109
  }
110
 
111
  except Exception as e:
@@ -117,7 +132,8 @@ def check_and_run_script(config):
117
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
118
  'username': config['username'],
119
  'script_name': script_name,
120
- 'runtime': "N/A"
 
121
  }
122
  finally:
123
  if client:
@@ -130,23 +146,24 @@ def check_all_vps():
130
  check_and_run_script(config)
131
 
132
  # 创建表格头
133
- table = "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+\n"
134
- table += "| Index | Hostname | Script Name | Status | Last Check | Username | Runtime |\n"
135
- table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+\n"
136
 
137
  # 添加每个VPS的状态
138
  for key, status in vps_status.items():
139
  hostname, script_name = key.split(':')
140
- table += "| {:<7} | {:<21} | {:<16} | {:<8} | {:<23} | {:<8} | {:<8} |\n".format(
141
  status['index'],
142
  hostname[:21],
143
  script_name[:16],
144
  status['status'][:8],
145
  status['last_check'],
146
  status['username'][:8],
147
- status['runtime'][:8]
 
148
  )
149
- table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+\n"
150
 
151
  logger.info("\n" + table)
152
 
@@ -163,6 +180,7 @@ def index():
163
  <th>Last Check</th>
164
  <th>Username</th>
165
  <th>Runtime</th>
 
166
  </tr>
167
  {% for key, data in vps_status.items() %}
168
  <tr>
@@ -173,6 +191,7 @@ def index():
173
  <td>{{ data.last_check }}</td>
174
  <td>{{ data.username }}</td>
175
  <td>{{ data.runtime }}</td>
 
176
  </tr>
177
  {% endfor %}
178
  </table>
 
72
 
73
  script_path = config['script_path']
74
  script_name = os.path.basename(script_path)
75
+ key = f"{config['hostname']}:{script_name}"
76
+
77
+ # 获取上次保存的 PID(如果有)
78
+ last_pid = vps_status.get(key, {}).get('pid', None)
79
+
80
+ # 检查进程是否在运行
81
+ if last_pid:
82
+ check_command = f"ps -p {last_pid} -o pid,etime,args"
83
+ else:
84
+ check_command = 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 = last_pid
93
+ runtime = parts[1] if len(parts) > 1 else "Unknown"
94
  else:
95
+ pid = parts[1] if len(parts) > 1 else "Unknown"
96
+ runtime = parts[9] if len(parts) > 9 else "Unknown"
97
+ status = "Running"
98
+ logger.info(f"Script {script_name} is running. PID: {pid}, Runtime: {runtime}")
99
  else:
100
+ logger.info(f"Script {script_name} not running. Attempting to restart.")
101
+ restart_command = f"nohup /bin/sh {script_path} > /dev/null 2>&1 & echo $!"
102
  stdin, stdout, stderr = client.exec_command(restart_command)
103
+ new_pid = stdout.read().decode('utf-8').strip()
104
 
105
+ if new_pid.isdigit():
106
+ pid = new_pid
107
  runtime = "Just started"
108
+ status = "Restarted"
109
+ logger.info(f"Script {script_name} restarted. New PID: {pid}")
110
  else:
111
+ pid = "N/A"
 
112
  runtime = "N/A"
113
+ status = "Restart Failed"
114
+ logger.error(f"Failed to restart script {script_name}")
115
 
 
116
  vps_status[key] = {
117
  'index': config['index'],
118
  'status': status,
119
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
120
  'username': config['username'],
121
  'script_name': script_name,
122
+ 'runtime': runtime,
123
+ 'pid': pid
124
  }
125
 
126
  except Exception as e:
 
132
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
133
  'username': config['username'],
134
  'script_name': script_name,
135
+ 'runtime': "N/A",
136
+ 'pid': "N/A"
137
  }
138
  finally:
139
  if client:
 
146
  check_and_run_script(config)
147
 
148
  # 创建表格头
149
+ table = "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
150
+ table += "| Index | Hostname | Script Name | Status | Last Check | Username | Runtime | PID |\n"
151
+ table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
152
 
153
  # 添加每个VPS的状态
154
  for key, status in vps_status.items():
155
  hostname, script_name = key.split(':')
156
+ table += "| {:<7} | {:<21} | {:<16} | {:<8} | {:<23} | {:<8} | {:<8} | {:<5} |\n".format(
157
  status['index'],
158
  hostname[:21],
159
  script_name[:16],
160
  status['status'][:8],
161
  status['last_check'],
162
  status['username'][:8],
163
+ status['runtime'][:8],
164
+ status['pid'][:5]
165
  )
166
+ table += "+---------+-----------------------+------------------+----------+-------------------------+----------+----------+-------+\n"
167
 
168
  logger.info("\n" + table)
169
 
 
180
  <th>Last Check</th>
181
  <th>Username</th>
182
  <th>Runtime</th>
183
+ <th>PID</th>
184
  </tr>
185
  {% for key, data in vps_status.items() %}
186
  <tr>
 
191
  <td>{{ data.last_check }}</td>
192
  <td>{{ data.username }}</td>
193
  <td>{{ data.runtime }}</td>
194
+ <td>{{ data.pid }}</td>
195
  </tr>
196
  {% endfor %}
197
  </table>