lbls888 commited on
Commit
94a300c
1 Parent(s): c57e3c9

Update vps_monitor.py

Browse files
Files changed (1) hide show
  1. vps_monitor.py +48 -62
vps_monitor.py CHANGED
@@ -39,24 +39,18 @@ def get_vps_configs():
39
  }
40
  configs.append(config)
41
 
42
- # 添加调试输出
43
- logger.info(f"Config {index}: {config}")
44
- print(f"Config {index}: {config}")
45
- sys.stdout.flush()
46
 
47
  index += 1
48
  return configs
49
 
50
  def check_and_run_script(config):
51
  logger.info(f"Checking VPS {config['index']}: {config['hostname']}")
52
- print(f"Checking VPS {config['index']}: {config['hostname']}")
53
- sys.stdout.flush()
54
  client = None
55
  try:
56
  client = paramiko.SSHClient()
57
  client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
58
 
59
- logger.info(f"Connecting to {config['hostname']}")
60
  client.connect(
61
  hostname=config['hostname'],
62
  username=config['username'],
@@ -67,28 +61,25 @@ def check_and_run_script(config):
67
  script_path = config['script_path']
68
  script_name = os.path.basename(script_path)
69
 
70
- # 检查脚本是否正在运行 (使用 ps 命令,适用于FreeBSD)
71
- check_command = f"ps aux | grep {script_name} | grep -v grep"
72
  stdin, stdout, stderr = client.exec_command(check_command)
73
- if stdout.read():
 
 
74
  status = "Running"
75
  logger.info(f"Script is running on {config['hostname']}")
76
  else:
77
  logger.info(f"Script not running on {config['hostname']}. Executing restart script.")
78
- restart_command = f"/bin/sh {script_path}" # 使用完整路径的sh
79
  stdin, stdout, stderr = client.exec_command(restart_command)
80
- exit_status = stdout.channel.recv_exit_status()
81
 
82
- if exit_status == 0:
83
- status = "Restarted"
84
- logger.info(f"Restart script executed successfully on {config['hostname']}")
85
- else:
86
- error_output = stderr.read().decode('utf-8')
87
- status = f"Error: {error_output}"
88
- logger.error(f"Error executing restart script on {config['hostname']}: {error_output}")
89
 
90
- vps_status[config['hostname']] = {
91
  'index': config['index'],
 
92
  'status': status,
93
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
94
  'username': config['username']
@@ -96,8 +87,9 @@ def check_and_run_script(config):
96
 
97
  except Exception as e:
98
  logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']}: {str(e)}")
99
- vps_status[config['hostname']] = {
100
  'index': config['index'],
 
101
  'status': f"Error: {str(e)}",
102
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
103
  'username': config['username']
@@ -105,52 +97,62 @@ def check_and_run_script(config):
105
  finally:
106
  if client:
107
  client.close()
108
- logger.info(f"SSH connection closed for VPS {config['index']}: {config['hostname']}")
109
- logger.info(f"Finished checking VPS {config['index']}: {config['hostname']}")
110
- print(f"Finished checking VPS {config['index']}: {config['hostname']}")
111
- sys.stdout.flush()
112
 
113
  def check_all_vps():
114
  logger.info("Starting VPS check")
115
- print("Starting VPS check")
116
- sys.stdout.flush()
117
  vps_configs = get_vps_configs()
118
  for config in vps_configs:
119
  check_and_run_script(config)
120
- logger.info("Finished VPS check")
121
- for hostname, status in vps_status.items():
122
- print(f"VPS {status['index']} - {hostname}: Status: {status['status']}, Username: {status['username']}")
123
- sys.stdout.flush()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
 
125
  @app.route('/')
126
  def index():
127
  html = '''
128
- <h1>VPS Status Overview</h1>
129
  <table border="1">
130
  <tr>
131
  <th>Index</th>
132
  <th>Hostname</th>
133
  <th>Status</th>
134
  <th>Last Check</th>
135
- <th>Username</th>
136
  </tr>
137
- {% for hostname, data in vps_status.items() %}
 
138
  <tr>
139
- <td>{{ data.index }}</td>
140
- <td><a href="/status/{{ hostname }}">{{ hostname }}</a></td>
141
- <td>{{ data.status }}</td>
142
- <td>{{ data.last_check }}</td>
143
- <td>{{ data.username }}</td>
144
  </tr>
145
  {% endfor %}
146
  </table>
147
  '''
148
  return render_template_string(html, vps_status=vps_status)
149
 
150
- @app.route('/status/<hostname>')
151
- def vps_status_detail(hostname):
152
- if hostname in vps_status:
153
- return jsonify(vps_status[hostname])
154
  else:
155
  return jsonify({"error": "VPS not found"}), 404
156
 
@@ -165,37 +167,22 @@ def main():
165
  global start_time
166
  start_time = time.time()
167
 
168
- print("===== VPS monitoring script is starting =====")
169
- sys.stdout.flush()
170
- logger.info("===== VPS monitoring script started =====")
171
 
172
  flask_thread = Thread(target=run_flask)
173
  flask_thread.start()
174
  logger.info("Flask server started in background")
175
- print("Flask server started in background")
176
- sys.stdout.flush()
177
 
178
  vps_configs = get_vps_configs()
179
  logger.info(f"Found {len(vps_configs)} VPS configurations")
180
- print(f"Found {len(vps_configs)} VPS configurations")
181
- sys.stdout.flush()
182
- for config in vps_configs:
183
- logger.info(f"VPS configured: {config['hostname']}")
184
- print(f"VPS configured: {config['hostname']}")
185
- sys.stdout.flush()
186
 
187
  logger.info("Running initial VPS check")
188
- print("Running initial VPS check")
189
- sys.stdout.flush()
190
  check_all_vps()
191
 
192
  schedule.every(15).minutes.do(check_all_vps)
193
  logger.info("Scheduled VPS check every 15 minutes")
194
- print("Scheduled VPS check every 15 minutes")
195
- sys.stdout.flush()
196
 
197
- print("===== VPS monitoring script is running =====")
198
- sys.stdout.flush()
199
 
200
  heartbeat_count = 0
201
  while True:
@@ -203,8 +190,7 @@ def main():
203
  time.sleep(60)
204
  heartbeat_count += 1
205
  if heartbeat_count % 5 == 0: # 每5分钟输出一次心跳信息
206
- print(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
207
- sys.stdout.flush()
208
 
209
  if __name__ == "__main__":
210
  main()
 
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'],
 
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['index']] = {
81
  'index': config['index'],
82
+ 'hostname': config['hostname'],
83
  'status': status,
84
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
85
  'username': config['username']
 
87
 
88
  except Exception as e:
89
  logger.error(f"Error occurred while checking VPS {config['index']} - {config['hostname']}: {str(e)}")
90
+ vps_status[config['index']] = {
91
  'index': config['index'],
92
+ 'hostname': config['hostname'],
93
  'status': f"Error: {str(e)}",
94
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
95
  'username': config['username']
 
97
  finally:
98
  if client:
99
  client.close()
 
 
 
 
100
 
101
  def check_all_vps():
102
  logger.info("Starting VPS check")
 
 
103
  vps_configs = get_vps_configs()
104
  for config in vps_configs:
105
  check_and_run_script(config)
106
+
107
+ # 创建表格头
108
+ table = "+---------+-----------------------+----------+-------------------------+----------+\n"
109
+ table += "| Index | Hostname | Status | Last Check | 用户名 |\n"
110
+ table += "+---------+-----------------------+----------+-------------------------+----------+\n"
111
+
112
+ # 添加每个VPS的状态
113
+ for index in sorted(vps_status.keys()):
114
+ status = vps_status[index]
115
+ table += "| {:<7} | {:<21} | {:<8} | {:<23} | {:<8} |\n".format(
116
+ status['index'],
117
+ status['hostname'][:21],
118
+ status['status'][:8],
119
+ status['last_check'],
120
+ status['username'][:8]
121
+ )
122
+ table += "+---------+-----------------------+----------+-------------------------+----------+\n"
123
+
124
+ logger.info("\n" + table)
125
 
126
  @app.route('/')
127
  def index():
128
  html = '''
129
+ <h1>VPS Status 概述</h1>
130
  <table border="1">
131
  <tr>
132
  <th>Index</th>
133
  <th>Hostname</th>
134
  <th>Status</th>
135
  <th>Last Check</th>
136
+ <th>用户名</th>
137
  </tr>
138
+ {% for index in vps_status.keys()|sort %}
139
+ {% set data = vps_status[index] %}
140
  <tr>
141
+ <td>{{ data['index'] }}</td>
142
+ <td><a href="/status/{{ data['index'] }}">{{ data['hostname'] }}</a></td>
143
+ <td>{{ data['status'] }}</td>
144
+ <td>{{ data['last_check'] }}</td>
145
+ <td>{{ data['username'] }}</td>
146
  </tr>
147
  {% endfor %}
148
  </table>
149
  '''
150
  return render_template_string(html, vps_status=vps_status)
151
 
152
+ @app.route('/status/<int:index>')
153
+ def vps_status_detail(index):
154
+ if index in vps_status:
155
+ return jsonify(vps_status[index])
156
  else:
157
  return jsonify({"error": "VPS not found"}), 404
158
 
 
167
  global start_time
168
  start_time = time.time()
169
 
170
+ logger.info("===== VPS monitoring script is starting =====")
 
 
171
 
172
  flask_thread = Thread(target=run_flask)
173
  flask_thread.start()
174
  logger.info("Flask server started in background")
 
 
175
 
176
  vps_configs = get_vps_configs()
177
  logger.info(f"Found {len(vps_configs)} VPS configurations")
 
 
 
 
 
 
178
 
179
  logger.info("Running initial VPS check")
 
 
180
  check_all_vps()
181
 
182
  schedule.every(15).minutes.do(check_all_vps)
183
  logger.info("Scheduled VPS check every 15 minutes")
 
 
184
 
185
+ logger.info("===== VPS monitoring script is running =====")
 
186
 
187
  heartbeat_count = 0
188
  while True:
 
190
  time.sleep(60)
191
  heartbeat_count += 1
192
  if heartbeat_count % 5 == 0: # 每5分钟输出一次心跳信息
193
+ logger.info(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
 
194
 
195
  if __name__ == "__main__":
196
  main()