xjf6b commited on
Commit
6eeb271
·
verified ·
1 Parent(s): 8eb57c1

Update vps_monitor.py

Browse files
Files changed (1) hide show
  1. vps_monitor.py +33 -45
vps_monitor.py CHANGED
@@ -6,21 +6,32 @@ import sys
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',
18
- handlers=[
19
- logging.StreamHandler(sys.stdout),
20
- logging.StreamHandler(sys.stderr)
21
- ]
22
- )
 
 
 
 
 
 
23
  logger = logging.getLogger()
 
 
24
 
25
  def get_vps_configs():
26
  configs = []
@@ -52,18 +63,13 @@ def get_vps_configs():
52
  }
53
  configs.append(config)
54
 
55
- # 添加调试输出
56
  logger.info(f"Config {index}: {hostname}, {username}, {script_paths}")
57
- print(f"Config {index}: {hostname}, {username}, {script_paths}")
58
- sys.stdout.flush()
59
 
60
  index += 1
61
  return configs
62
 
63
  def check_and_run_script(config):
64
  logger.info(f"Checking VPS {config['index']}: {config['hostname']} - {config['script_path']}")
65
- print(f"Checking VPS {config['index']}: {config['hostname']} - {config['script_path']}")
66
- sys.stdout.flush()
67
  client = None
68
  try:
69
  client = paramiko.SSHClient()
@@ -80,24 +86,25 @@ def check_and_run_script(config):
80
  script_path = config['script_path']
81
  script_name = os.path.basename(script_path)
82
 
83
- # 检查脚本是否正在运行 (使用 ps 命令,适用于FreeBSD)
84
  check_command = f"ps aux | grep {script_name} | grep -v grep"
85
  stdin, stdout, stderr = client.exec_command(check_command)
86
  if stdout.read():
87
- status = "Running"
88
  logger.info(f"Script {script_name} is running on {config['hostname']}")
89
  else:
90
- logger.info(f"Script {script_name} not running on {config['hostname']}. Executing restart script.")
91
- restart_command = f"/bin/sh {script_path}" # 使用完整路径的sh
92
  stdin, stdout, stderr = client.exec_command(restart_command)
93
  exit_status = stdout.channel.recv_exit_status()
94
 
95
  if exit_status == 0:
96
- status = "Restarted"
97
  logger.info(f"Restart script {script_name} executed successfully on {config['hostname']}")
 
 
98
  else:
99
  error_output = stderr.read().decode('utf-8')
100
- status = f"Error: {error_output}"
101
  logger.error(f"Error executing restart script {script_name} on {config['hostname']}: {error_output}")
102
 
103
  key = f"{config['hostname']}:{script_name}"
@@ -114,7 +121,7 @@ def check_and_run_script(config):
114
  key = f"{config['hostname']}:{script_name}"
115
  vps_status[key] = {
116
  'index': config['index'],
117
- 'status': f"Error: {str(e)}",
118
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
119
  'username': config['username'],
120
  'script_name': script_name
@@ -124,20 +131,15 @@ def check_and_run_script(config):
124
  client.close()
125
  logger.info(f"SSH connection closed for VPS {config['index']}: {config['hostname']}")
126
  logger.info(f"Finished checking VPS {config['index']}: {config['hostname']} - {script_name}")
127
- print(f"Finished checking VPS {config['index']}: {config['hostname']} - {script_name}")
128
- sys.stdout.flush()
129
 
130
  def check_all_vps():
131
- logger.info("Starting VPS check")
132
- print("Starting VPS check")
133
- sys.stdout.flush()
134
  vps_configs = get_vps_configs()
135
  for config in vps_configs:
136
  check_and_run_script(config)
137
- logger.info("Finished VPS check")
138
  for key, status in vps_status.items():
139
- print(f"VPS {status['index']} - {key}: Status: {status['status']}, Username: {status['username']}, Script: {status['script_name']}")
140
- sys.stdout.flush()
141
 
142
  @app.route('/')
143
  def index():
@@ -184,37 +186,24 @@ def main():
184
  global start_time
185
  start_time = time.time()
186
 
187
- print("===== VPS monitoring script is starting =====")
188
- sys.stdout.flush()
189
- logger.info("===== VPS monitoring script started =====")
190
 
191
  flask_thread = Thread(target=run_flask)
192
  flask_thread.start()
193
  logger.info("Flask server started in background")
194
- print("Flask server started in background")
195
- sys.stdout.flush()
196
 
197
  vps_configs = get_vps_configs()
198
  logger.info(f"Found {len(vps_configs)} VPS configurations")
199
- print(f"Found {len(vps_configs)} VPS configurations")
200
- sys.stdout.flush()
201
  for config in vps_configs:
202
  logger.info(f"VPS configured: {config['hostname']} - {config['script_path']}")
203
- print(f"VPS configured: {config['hostname']} - {config['script_path']}")
204
- sys.stdout.flush()
205
 
206
  logger.info("Running initial VPS check")
207
- print("Running initial VPS check")
208
- sys.stdout.flush()
209
  check_all_vps()
210
 
211
  schedule.every(15).minutes.do(check_all_vps)
212
  logger.info("Scheduled VPS check every 15 minutes")
213
- print("Scheduled VPS check every 15 minutes")
214
- sys.stdout.flush()
215
 
216
- print("===== VPS monitoring script is running =====")
217
- sys.stdout.flush()
218
 
219
  heartbeat_count = 0
220
  while True:
@@ -222,8 +211,7 @@ def main():
222
  time.sleep(60)
223
  heartbeat_count += 1
224
  if heartbeat_count % 5 == 0: # 每5分钟输出一次心跳信息
225
- print(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
226
- sys.stdout.flush()
227
 
228
  if __name__ == "__main__":
229
  main()
 
6
  from flask import Flask, jsonify, render_template_string
7
  from threading import Thread
8
  import logging
9
+ from colorama import init, Fore, Back, Style
10
+
11
+ init(autoreset=True) # 初始化 colorama
12
 
13
  app = Flask(__name__)
14
 
15
  vps_status = {}
16
 
17
  # 设置日志
18
+ class ColoredFormatter(logging.Formatter):
19
+ def format(self, record):
20
+ if record.levelno == logging.INFO:
21
+ record.msg = f"{Fore.GREEN}{record.msg}{Style.RESET_ALL}"
22
+ elif record.levelno == logging.WARNING:
23
+ record.msg = f"{Fore.YELLOW}{record.msg}{Style.RESET_ALL}"
24
+ elif record.levelno == logging.ERROR:
25
+ record.msg = f"{Fore.RED}{record.msg}{Style.RESET_ALL}"
26
+ return super().format(record)
27
+
28
+ formatter = ColoredFormatter('%(asctime)s - %(levelname)s - %(message)s')
29
+ handler = logging.StreamHandler(sys.stdout)
30
+ handler.setFormatter(formatter)
31
+
32
  logger = logging.getLogger()
33
+ logger.setLevel(logging.INFO)
34
+ logger.addHandler(handler)
35
 
36
  def get_vps_configs():
37
  configs = []
 
63
  }
64
  configs.append(config)
65
 
 
66
  logger.info(f"Config {index}: {hostname}, {username}, {script_paths}")
 
 
67
 
68
  index += 1
69
  return configs
70
 
71
  def check_and_run_script(config):
72
  logger.info(f"Checking VPS {config['index']}: {config['hostname']} - {config['script_path']}")
 
 
73
  client = None
74
  try:
75
  client = paramiko.SSHClient()
 
86
  script_path = config['script_path']
87
  script_name = os.path.basename(script_path)
88
 
 
89
  check_command = f"ps aux | grep {script_name} | grep -v grep"
90
  stdin, stdout, stderr = client.exec_command(check_command)
91
  if stdout.read():
92
+ status = f"{Fore.GREEN}Running{Style.RESET_ALL}"
93
  logger.info(f"Script {script_name} is running on {config['hostname']}")
94
  else:
95
+ logger.warning(f"Script {script_name} not running on {config['hostname']}. Executing restart script.")
96
+ restart_command = f"/bin/sh {script_path}"
97
  stdin, stdout, stderr = client.exec_command(restart_command)
98
  exit_status = stdout.channel.recv_exit_status()
99
 
100
  if exit_status == 0:
101
+ status = f"{Fore.YELLOW}Restarted{Style.RESET_ALL}"
102
  logger.info(f"Restart script {script_name} executed successfully on {config['hostname']}")
103
+ output = stdout.read().decode('utf-8')
104
+ logger.info(f"Restart output: {output}")
105
  else:
106
  error_output = stderr.read().decode('utf-8')
107
+ status = f"{Fore.RED}Error{Style.RESET_ALL}"
108
  logger.error(f"Error executing restart script {script_name} on {config['hostname']}: {error_output}")
109
 
110
  key = f"{config['hostname']}:{script_name}"
 
121
  key = f"{config['hostname']}:{script_name}"
122
  vps_status[key] = {
123
  'index': config['index'],
124
+ 'status': f"{Fore.RED}Error: {str(e)}{Style.RESET_ALL}",
125
  'last_check': time.strftime('%Y-%m-%d %H:%M:%S'),
126
  'username': config['username'],
127
  'script_name': script_name
 
131
  client.close()
132
  logger.info(f"SSH connection closed for VPS {config['index']}: {config['hostname']}")
133
  logger.info(f"Finished checking VPS {config['index']}: {config['hostname']} - {script_name}")
 
 
134
 
135
  def check_all_vps():
136
+ logger.info(f"{Back.BLUE}{Fore.WHITE}Starting VPS check{Style.RESET_ALL}")
 
 
137
  vps_configs = get_vps_configs()
138
  for config in vps_configs:
139
  check_and_run_script(config)
140
+ logger.info(f"{Back.BLUE}{Fore.WHITE}Finished VPS check{Style.RESET_ALL}")
141
  for key, status in vps_status.items():
142
+ logger.info(f"VPS {status['index']} - {key}: Status: {status['status']}, Username: {status['username']}, Script: {status['script_name']}")
 
143
 
144
  @app.route('/')
145
  def index():
 
186
  global start_time
187
  start_time = time.time()
188
 
189
+ logger.info("===== VPS monitoring script is starting =====")
 
 
190
 
191
  flask_thread = Thread(target=run_flask)
192
  flask_thread.start()
193
  logger.info("Flask server started in background")
 
 
194
 
195
  vps_configs = get_vps_configs()
196
  logger.info(f"Found {len(vps_configs)} VPS configurations")
 
 
197
  for config in vps_configs:
198
  logger.info(f"VPS configured: {config['hostname']} - {config['script_path']}")
 
 
199
 
200
  logger.info("Running initial VPS check")
 
 
201
  check_all_vps()
202
 
203
  schedule.every(15).minutes.do(check_all_vps)
204
  logger.info("Scheduled VPS check every 15 minutes")
 
 
205
 
206
+ logger.info("===== VPS monitoring script is running =====")
 
207
 
208
  heartbeat_count = 0
209
  while True:
 
211
  time.sleep(60)
212
  heartbeat_count += 1
213
  if heartbeat_count % 5 == 0: # 每5分钟输出一次心跳信息
214
+ logger.info(f"Heartbeat: Script is still running. Uptime: {heartbeat_count} minutes")
 
215
 
216
  if __name__ == "__main__":
217
  main()