forked from Zhh9126/linuxcheck
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1796 lines (1626 loc) · 75.1 KB
/
Copy pathmain.py
File metadata and controls
1796 lines (1626 loc) · 75.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
"""
操作系统批量巡检工具 v3.2 (性能优化版)
功能:
- 生成 Excel 批量巡检模板,主机名自动探测
- 并发 SSH 远程执行系统巡检 (优化防卡死)
- 检测系统信息、安全、僵尸进程、磁盘I/O、中间件端口、性能、服务、日志、网络
- 定时任务精准过滤(剔除环境变量,只显示真实任务)
- 网络连接状态使用 ss 命令,无 netstat 依赖
- 生成 Word 格式专业报告(含运维单位/人员、状态着色、进度条)
- 报告文件名格式:IP地址_巡检报告_时间.docx
- 新增:深度中间件巡检 (Nginx/Redis/Kafka/ES/Tomcat/MySQL/Oracle/达梦等)
- 新增:DEBUG 级详细执行日志,便于排查问题
- 修复:加载Excel时自动检测并加密明文密码,防止泄露
- 优化:解决 yum check-update 等命令导致的巡检卡死问题
"""
# ------------------------------------------------------------
# 强制导入 idna 编码,解决 PyInstaller 打包后编码缺失问题
# ------------------------------------------------------------
import encodings.idna
import warnings
warnings.filterwarnings("ignore", category=DeprecationWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
import os
import sys
import logging
import subprocess
import platform
import re
import getpass
import base64
import time
import select
from datetime import datetime
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
# ------------------------------------------------------------
# 配置双日志系统:主日志(INFO) + 调试日志(DEBUG)
# ------------------------------------------------------------
logging.getLogger("paramiko").setLevel(logging.WARNING)
# 主日志 (仅文件)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG) # 记录所有级别
if not logger.handlers:
# 普通 INFO 日志
fh_info = logging.FileHandler('/tmp/os_batch_inspector.log', encoding='utf-8')
fh_info.setLevel(logging.INFO)
fh_info.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
# 详细 DEBUG 日志 (用于排查问题)
fh_debug = logging.FileHandler('/tmp/os_inspector_debug.log', encoding='utf-8')
fh_debug.setLevel(logging.DEBUG)
fh_debug.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'))
logger.addHandler(fh_info)
logger.addHandler(fh_debug)
# ------------------------------------------------------------
# 依赖库检查与导入
# ------------------------------------------------------------
def check_dependencies():
missing = []
try:
import paramiko
except ImportError:
missing.append("paramiko")
try:
import docx
from docx.shared import Cm, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
except ImportError:
missing.append("python-docx")
try:
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment
except ImportError:
missing.append("openpyxl")
try:
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
except ImportError:
missing.append("cryptography")
if missing:
print("❌ 缺少必需库: " + ", ".join(missing))
print("请执行: pip install " + " ".join(missing))
sys.exit(1)
check_dependencies()
# 导入并设置全局可用标志
try:
import paramiko
except ImportError:
paramiko = None
try:
import docx
from docx.shared import Cm, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.oxml.ns import qn
HAS_DOCX = True
except ImportError:
HAS_DOCX = False
try:
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
HAS_EXCEL = True
except ImportError:
HAS_EXCEL = False
try:
from cryptography.fernet import Fernet
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
except ImportError:
Fernet = None
if paramiko is None:
print("❌ paramiko 未安装,无法进行远程 SSH 巡检")
sys.exit(1)
# ------------------------------------------------------------
# 工具函数
# ------------------------------------------------------------
def clean_string(text):
"""清理 XML 非法字符"""
if text is None:
return ""
text = str(text)
cleaned = ""
for ch in text:
if ch == '\t' or ch == '\n' or ch == '\r':
cleaned += ch
elif ord(ch) >= 32:
cleaned += ch
cleaned = re.sub(r'[\x00-\x08\x0b-\x0c\x0e-\x1f\x7f-\x9f]', '', cleaned)
return cleaned.strip()
def run_local_cmd(cmd, timeout=30):
"""执行本地 shell 命令,返回 stdout, stderr, rc (强制超时保护)"""
logger.debug(f"[本地命令] 执行: {cmd} (超时: {timeout}s)")
try:
proc = subprocess.run(
cmd,
shell=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
timeout=timeout,
encoding='utf-8',
errors='ignore'
)
logger.debug(f"[本地命令] 返回码: {proc.returncode}, 输出: {proc.stdout.strip()[:200]}")
return proc.stdout.strip(), proc.stderr.strip(), proc.returncode
except subprocess.TimeoutExpired:
logger.warning(f"[本地命令] 超时 ({timeout}s): {cmd}")
return "", "Timeout", -1
except Exception as e:
logger.error(f"[本地命令] 异常: {cmd}, {e}")
return "", str(e), -1
def safe_int(val, default=0):
"""安全转换为整数"""
if val is None:
return default
try:
if isinstance(val, str) and val.strip().isdigit():
return int(val.strip())
return int(val) if not isinstance(val, str) else default
except (ValueError, TypeError):
return default
def is_error_output(output):
"""判断命令输出是否为错误信息"""
if not output:
return False
error_indicators = ("错误:", "SSH执行失败:", "命令执行失败", "Timeout")
return any(output.startswith(e) for e in error_indicators)
# ------------------------------------------------------------
# 密码加密管理器
# ------------------------------------------------------------
class PasswordEncryptor:
def __init__(self, master_key=None):
self.master_key = master_key or self._get_default_master_key()
self.fernet = self._create_fernet(self.master_key)
def _get_default_master_key(self):
try:
machine_id = platform.node()
system_info = platform.system() + platform.release()
base_key = f"{machine_id}_{system_info}_os_inspector_v2"
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=32,
salt=b'os_inspector_salt',
iterations=100000,
)
key = Fernet.generate_key() if not base_key else base64.urlsafe_b64encode(kdf.derive(base_key.encode()))
return key
except:
return Fernet.generate_key()
def _create_fernet(self, key):
try:
return Fernet(key)
except:
return Fernet(Fernet.generate_key())
def encrypt_password(self, password):
if not password:
return ""
try:
encrypted = self.fernet.encrypt(str(password).encode('utf-8'))
return base64.urlsafe_b64encode(encrypted).decode('utf-8')
except:
return str(password)
def decrypt_password(self, encrypted):
if not encrypted:
return ""
try:
encrypted_bytes = base64.urlsafe_b64decode(str(encrypted).encode('utf-8'))
return self.fernet.decrypt(encrypted_bytes).decode('utf-8')
except:
return str(encrypted)
# ------------------------------------------------------------
# SSH 远程执行器 (优化版:防卡死、详细日志)
# ------------------------------------------------------------
class SSHExecutor:
def __init__(self, host_info, encryptor):
self.host_info = host_info
self.encryptor = encryptor
self.timeout = 120
self.logger = logging.getLogger(f"SSH.{host_info.get('host', 'unknown')}")
self.logger.debug(f"SSHExecutor 初始化: {host_info.get('host')}:{host_info.get('ssh_port', 22)}")
def execute_command(self, command, timeout=None, retry=1):
"""执行远程命令,优化缓冲区读取防止卡死"""
if timeout is None:
timeout = self.timeout
host = self.host_info['host']
port = self.host_info.get('ssh_port', 22)
user = self.host_info.get('ssh_user', 'root')
self.logger.debug(f"[SSH] 准备执行命令 ({host}): {command} (超时: {timeout}s)")
for attempt in range(retry + 1):
ssh = None
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_password = self.host_info.get('ssh_password', '')
if ssh_password and self._is_encrypted_format(ssh_password):
ssh_password = self.encryptor.decrypt_password(ssh_password)
self.logger.debug(f"[SSH] 尝试连接 (尝试 {attempt+1}/{retry+1})...")
ssh.connect(
hostname=host,
port=port,
username=user,
password=ssh_password,
timeout=30,
banner_timeout=30,
auth_timeout=30,
allow_agent=False,
look_for_keys=False,
compress=True
)
self.logger.debug(f"[SSH] 连接建立成功")
# 移除 get_pty=True,避免交互式挂起
stdin, stdout, stderr = ssh.exec_command(command, timeout=timeout)
# 使用 select 轮询,防止缓冲区满导致死锁
channel = stdout.channel
channel.settimeout(timeout)
stdout_data = []
stderr_data = []
start_time = time.time()
while not channel.exit_status_ready():
if time.time() - start_time > timeout:
self.logger.error(f"[SSH] 命令执行超时 ({timeout}s)")
raise TimeoutError("Command execution timeout")
# 检查 stdout 是否有数据
if channel.recv_ready():
stdout_data.append(channel.recv(4096).decode('utf-8', errors='ignore'))
# 检查 stderr 是否有数据
if channel.recv_stderr_ready():
stderr_data.append(channel.recv_stderr(4096).decode('utf-8', errors='ignore'))
time.sleep(0.1)
# 读取剩余数据
while channel.recv_ready():
stdout_data.append(channel.recv(4096).decode('utf-8', errors='ignore'))
while channel.recv_stderr_ready():
stderr_data.append(channel.recv_stderr(4096).decode('utf-8', errors='ignore'))
output = ''.join(stdout_data).strip()
error = ''.join(stderr_data).strip()
exit_status = channel.recv_exit_status()
self.logger.debug(f"[SSH] 命令执行完毕,退出码: {exit_status}")
self.logger.debug(f"[SSH] stdout: {output[:300]}")
if error:
self.logger.debug(f"[SSH] stderr: {error[:300]}")
# 特殊处理 crontab
if exit_status != 0 and not output:
if "no crontab" in error.lower():
return ""
return f"错误: {error} (退出码: {exit_status})"
ssh.close()
return output
except TimeoutError as e:
self.logger.error(f"[SSH] 超时 (尝试 {attempt+1}/{retry+1}): {e}")
if attempt == retry:
return f"SSH执行失败: 超时 - {e}"
time.sleep(2)
except Exception as e:
self.logger.error(f"[SSH] 执行失败 (尝试 {attempt+1}/{retry+1}): {e}", exc_info=True)
if attempt == retry:
return f"SSH执行失败: {e}"
time.sleep(2)
finally:
if ssh:
try:
ssh.close()
except:
pass
return "SSH执行失败: 未知错误"
def _is_encrypted_format(self, password):
try:
return len(str(password)) > 50 and re.match(r'^[A-Za-z0-9-_]*={0,2}$', str(password))
except:
return False
# ------------------------------------------------------------
# 控制台美化输出
# ------------------------------------------------------------
class ConsolePrinter:
@staticmethod
def separator():
print("=" * 60)
@staticmethod
def title(title):
ConsolePrinter.separator()
print(f"🎯 {title}")
ConsolePrinter.separator()
@staticmethod
def success(msg):
print(f"✅ {msg}")
@staticmethod
def info(msg):
print(f"ℹ️ {msg}")
@staticmethod
def warning(msg):
print(f"⚠️ {msg}")
@staticmethod
def error(msg):
print(f"❌ {msg}")
# ------------------------------------------------------------
# 操作系统巡检核心类 (含深度中间件检查)
# ------------------------------------------------------------
class OSSysChecker:
def __init__(self, host_info=None, encryptor=None):
self.host_info = host_info
self.encryptor = encryptor
self.is_local = host_info is None
self.ssh_executor = None
if not self.is_local:
self.ssh_executor = SSHExecutor(host_info, encryptor)
self.results = {}
self._collect_basic_info()
def _execute(self, command, timeout=None):
"""统一执行命令入口,支持自定义超时"""
logger.debug(f"[Check] 执行检查命令: {command}")
if self.is_local:
# 本地执行:如果指定了timeout就用指定的,否则用默认30s
t = timeout if timeout else 30
out, _, rc = run_local_cmd(command, timeout=t)
if rc != 0 or is_error_output(out):
return ""
return out
else:
# 远程执行:传入timeout
out = self.ssh_executor.execute_command(command, timeout=timeout, retry=1)
if is_error_output(out):
return ""
return out
def _collect_basic_info(self):
self.hostname = self._get_hostname()
self.os_info = self._get_os_info()
self.kernel = self._get_kernel()
self.cpu_cores = self._get_cpu_cores()
self.mem_total = self._get_mem_total()
self.ip_address = self.host_info['host'] if self.host_info else self._get_ip_address()
self.uptime = self._get_uptime()
def _get_hostname(self):
out = self._execute("hostname")
return out.strip() if out else (self.host_info['host'] if self.host_info else platform.node())
def _get_os_info(self):
out = self._execute("cat /etc/os-release | grep PRETTY_NAME | cut -d= -f2 | tr -d '\"'")
if out:
return out.strip()
return self._execute("uname -sr") or "未知"
def _get_kernel(self):
out = self._execute("uname -r")
return out.strip() or platform.release()
def _get_cpu_cores(self):
out = self._execute("grep -c ^processor /proc/cpuinfo")
return safe_int(out, os.cpu_count() or 0)
def _get_mem_total(self):
out = self._execute("grep MemTotal /proc/meminfo | awk '{print $2}'")
mem_kb = safe_int(out)
if mem_kb > 0:
return f"{mem_kb // 1024} MB" if mem_kb < 1048576 else f"{mem_kb // 1048576} GB"
return "未知"
def _get_ip_address(self):
out = self._execute("hostname -I | awk '{print $1}'")
if out:
return out.strip()
out = self._execute("ip -4 addr show | grep -oP '(?<=inet\\s)\\d+(\\.\\d+){3}' | grep -v '127.0.0.1' | head -1")
return out.strip() or "未知"
def _get_uptime(self):
out = self._execute("uptime -p")
if out:
return out.replace('up ', '').strip()
out = self._execute("cat /proc/uptime | awk '{print int($1/86400)\"天 \"int(($1%86400)/3600)\"小时\"}'")
return out.strip() or "未知"
# ---------- 1. 系统基本信息 ----------
def check_system_basic(self):
data = [
["系统版本", self.os_info, "正常"],
["内核版本", self.kernel, "正常"],
["主机名", self.hostname, "已配置"],
["IP地址", self.ip_address, "已分配"],
["运行时间", self.uptime, "稳定"],
["CPU核心", f"{self.cpu_cores} 核心", "已识别"],
["总内存", self.mem_total, "已识别"]
]
self.results["系统基本信息"] = {"columns": ["属性", "值", "状态"], "data": data}
return data
# ---------- 2. 环境安全检查 ----------
def check_env_security(self):
path_env = self._execute("echo $PATH")
paths = path_env.split(':')
dangerous_paths = ["/", "/root", "/tmp", "/var/tmp", "/dev/shm"]
dangerous_found = []
writable_paths = []
# 优化:不再对每个PATH都执行test,减少命令执行次数
for p in paths[:10]: # 只检查前10个PATH,避免过多
if p in dangerous_paths:
dangerous_found.append(p)
if p:
if self.is_local:
if os.path.isdir(p) and os.access(p, os.W_OK):
writable_paths.append(p)
else:
# 远程检查合并为一条命令
pass
# 远程PATH检查优化:批量检查
if not self.is_local and paths:
# 构造一个批量检查脚本
cmd = "for p in " + ":".join(paths[:10]).replace(':', ' ') + "; do test -d $p -a -w $p && echo $p; done"
out = self._execute(cmd, timeout=10)
if out:
writable_paths = out.split('\n')
path_data = []
if dangerous_found:
path_data.append(["PATH危险路径", ", ".join(dangerous_found[:5]), "危险"])
if writable_paths:
path_data.append(["PATH可写路径", ", ".join(writable_paths[:5]), "警告"])
if not dangerous_found and not writable_paths:
path_data.append(["PATH环境变量", "检查正常", "正常"])
env_out = self._execute("env")
sensitive_keywords = ["PASSWORD", "SECRET", "KEY", "TOKEN", "CREDENTIAL", "PASS", "DB_PASS"]
sensitive_vars = []
for line in env_out.split('\n'):
for kw in sensitive_keywords:
if kw in line.upper():
var = line.split('=')[0]
sensitive_vars.append(f"{var}=****")
break
sensitive_data = []
if sensitive_vars:
sensitive_data.append(["敏感变量", "; ".join(sensitive_vars[:5]), "警告"])
else:
sensitive_data.append(["敏感环境变量", "未发现", "正常"])
env_files = ["/etc/profile", "/etc/bashrc", "~/.bashrc", "~/.bash_profile"]
file_perm_data = []
for f in env_files:
if self.is_local:
path = os.path.expanduser(f)
if os.path.exists(path):
stat = os.stat(path)
perms = oct(stat.st_mode)[-3:]
status = "安全权限" if int(perms) <= 644 else "不安全权限"
else:
perms, status = "不存在", "信息"
else:
stat_cmd = f"stat -c '%a' {f} 2>/dev/null || echo '不存在'"
perms = self._execute(stat_cmd)
if perms and perms != '不存在' and perms.isdigit():
status = "安全权限" if int(perms) <= 644 else "不安全权限"
else:
perms, status = "不存在", "信息"
file_perm_data.append([f, perms, status])
self.results["环境变量安全检测"] = {"columns": ["检查项", "详情", "状态"], "data": path_data + sensitive_data}
self.results["环境配置文件权限"] = {"columns": ["文件", "权限", "状态"], "data": file_perm_data}
# ---------- 3. 僵尸进程检测 ----------
def check_zombie_processes(self):
out = self._execute("ps aux | awk '$8==\"Z\"'")
zombies = []
for line in out.strip().split('\n'):
if line and 'awk' not in line and 'Z' in line:
parts = line.split()
if len(parts) >= 11:
pid = parts[1]
cmd = parts[10]
zombies.append([pid, cmd[:40]])
self.results["僵尸进程"] = {
"columns": ["PID", "命令"],
"data": zombies if zombies else [["无", "未发现僵尸进程"]]
}
# ---------- 4. 系统句柄分析 ----------
def check_file_handles(self):
sys_max = "未知"
sys_current = "未知"
sys_available = "未知"
usage_rate = 0.0
try:
if self.is_local:
with open('/proc/sys/fs/file-max', 'r') as f:
sys_max = int(f.read().strip())
with open('/proc/sys/fs/file-nr', 'r') as f:
parts = f.read().split()
sys_current = int(parts[0])
else:
max_out = self._execute("cat /proc/sys/fs/file-max")
if max_out and max_out.isdigit():
sys_max = int(max_out)
nr_out = self._execute("cat /proc/sys/fs/file-nr")
if nr_out:
parts = nr_out.strip().split()
if parts and parts[0].isdigit():
sys_current = int(parts[0])
if isinstance(sys_max, int) and isinstance(sys_current, int) and sys_max > 0:
sys_available = sys_max - sys_current
usage_rate = round((sys_current / sys_max) * 100, 2)
except:
pass
soft_limit = self._execute("ulimit -Sn") or "未知"
hard_limit = self._execute("ulimit -Hn") or "未知"
if usage_rate > 80:
usage_status = "危险"
elif usage_rate > 60:
usage_status = "警告"
else:
usage_status = "正常"
handle_summary = [
["系统级最大句柄数", sys_max, "已配置"],
["当前已使用句柄", sys_current, "正常"],
["句柄剩余可用", sys_available, "充足"],
["用户级软限制", soft_limit, "已设置"],
["用户级硬限制", hard_limit, "已设置"],
["句柄使用率", f"{usage_rate}%", usage_status]
]
self.results["系统句柄数分析"] = {"columns": ["项目", "值", "状态"], "data": handle_summary}
lsof_installed = self._execute("command -v lsof") != ""
process_handles = []
if lsof_installed:
# 优化:lsof 非常慢,这里限制超时
out = self._execute("lsof -n 2>/dev/null | awk '{print $2}' | sort | uniq -c | sort -nr | head -10", timeout=20)
if out:
for line in out.strip().split('\n'):
parts = line.strip().split()
if len(parts) >= 2:
count = parts[0]
pid = parts[1]
# 优化:不再循环调用 ps -p,而是一次性获取
proc_name = "未知"
count_val = safe_int(count)
if count_val > 1000:
status = "过高"
elif count_val > 500:
status = "偏多"
else:
status = "正常"
process_handles.append([pid, count_val, proc_name[:30], status])
else:
process_handles.append(["lsof执行超时/失败", "", "跳过进程句柄统计", "信息"])
else:
process_handles.append(["lsof未安装", "", "无法获取进程句柄信息", "警告"])
self.results["进程句柄TOP10"] = {
"columns": ["PID", "句柄数", "进程名", "状态"],
"data": process_handles
}
# ---------- 5. 磁盘 I/O 统计 ----------
def check_disk_io(self):
content = self._execute("cat /proc/diskstats")
disk_data = []
if content:
for line in content.strip().split('\n')[:10]:
parts = line.split()
if len(parts) >= 14:
dev = parts[2]
rd_ios = parts[3]
wr_ios = parts[7]
total = safe_int(rd_ios) + safe_int(wr_ios)
disk_data.append([dev, rd_ios, wr_ios, total])
self.results["磁盘I/O统计"] = {
"columns": ["设备", "读完成", "写完成", "总I/O次数"],
"data": disk_data if disk_data else [["无", "无法获取/proc/diskstats", "", ""]]
}
# ---------- 6. 深度中间件巡检 ----------
def check_middleware_detailled(self):
"""深度中间件检查:Nginx, Redis, Kafka, ES, Tomcat, 各类数据库"""
middleware_results = []
# 1. Nginx
logger.debug("[中间件] 检查 Nginx...")
nginx_ps = self._execute("ps aux | grep nginx | grep -v grep || true")
if nginx_ps:
version = self._execute("nginx -v 2>&1 || true", timeout=10)
middleware_results.append(["Nginx", "运行中", version[:50], "Web服务"])
# 2. Redis
logger.debug("[中间件] 检查 Redis...")
redis_ps = self._execute("ps aux | grep redis-server | grep -v grep || true")
if redis_ps:
version = self._execute("redis-cli --version || true", timeout=10)
middleware_results.append(["Redis", "运行中", version[:50], "缓存"])
# 3. Kafka
logger.debug("[中间件] 检查 Kafka...")
kafka_ps = self._execute("ps aux | grep kafka.Kafka | grep -v grep || true")
if kafka_ps:
middleware_results.append(["Kafka", "运行中", "JVM进程", "消息队列"])
# 4. Elasticsearch
logger.debug("[中间件] 检查 Elasticsearch...")
es_ps = self._execute("ps aux | grep elasticsearch | grep -v grep || true")
if es_ps:
middleware_results.append(["Elasticsearch", "运行中", "Java进程", "搜索引擎"])
# 5. Tomcat
logger.debug("[中间件] 检查 Tomcat...")
tomcat_ps = self._execute("ps aux | grep -E 'catalina|tomcat' | grep -v grep || true")
if tomcat_ps:
middleware_results.append(["Tomcat", "运行中", "Java容器", "Web中间件"])
# 6. MySQL
logger.debug("[中间件] 检查 MySQL...")
mysql_ps = self._execute("ps aux | grep mysqld | grep -v grep || true")
if mysql_ps:
# 移除可能卡住的 mysql --version 检查
middleware_results.append(["MySQL", "运行中", "进程存在", "数据库"])
# 7. Oracle (简单检查)
oracle_ps = self._execute("ps aux | grep ora_pmon | grep -v grep || true")
if oracle_ps:
middleware_results.append(["Oracle", "运行中", "PMON进程存在", "数据库"])
# 8. 达梦数据库
dmserver_ps = self._execute("ps aux | grep dmserver | grep -v grep || true")
if dmserver_ps:
middleware_results.append(["达梦数据库", "运行中", "dmserver进程", "国产数据库"])
if middleware_results:
self.results["深度中间件巡检"] = {
"columns": ["中间件", "状态", "版本/信息", "备注"],
"data": middleware_results
}
else:
self.results["深度中间件巡检"] = {
"columns": ["提示"],
"data": [["未在标准路径/进程中发现常见中间件"]]
}
# ---------- 7. 基础端口探测 ----------
def check_middleware(self):
out = self._execute("ss -tlnp 2>/dev/null")
if not out:
self.results["中间件端口状态"] = {"columns": ["错误"], "data": [["无法获取监听端口信息"]]}
return
middleware_map = {
'3306': 'MySQL', '6379': 'Redis', '27017': 'MongoDB',
'5432': 'PostgreSQL', '1521': 'Oracle', '5236': '达梦',
'80': 'HTTP', '443': 'HTTPS', '8080': 'Tomcat',
'2181': 'ZooKeeper', '9092': 'Kafka', '5672': 'RabbitMQ',
'15672': 'RabbitMQ管理', '9200': 'Elasticsearch',
'5601': 'Kibana', '9300': 'Elasticsearch', '8848': 'Nacos'
}
results = []
for line in out.split('\n'):
parts = line.strip().split()
if len(parts) >= 5:
proto = parts[0]
addr = parts[3]
port_part = addr.split(':')[-1]
if port_part.isdigit():
port = port_part
service = middleware_map.get(port, '未知')
proc = parts[-1] if 'users:' in line else ''
proc_name = ''
if 'pid=' in proc:
m = re.search(r'pid=(\d+),.*?process="?([^",]+)', proc)
if m:
proc_name = m.group(2)
if service != '未知' or (service == '未知' and proc_name):
results.append([port, service, proc_name, proto, '监听中'])
if results:
self.results["中间件端口状态"] = {
"columns": ["端口", "服务", "进程", "协议", "状态"],
"data": results
}
else:
self.results["中间件端口状态"] = {"columns": ["信息"], "data": [["未发现常见中间件端口"]]}
# ---------- 8. CPU性能 ----------
def check_performance(self):
cpu_model = "未知"
out = self._execute("grep -m1 'model name' /proc/cpuinfo | cut -d: -f2 | sed -e 's/^ *//'")
if out:
cpu_model = out.strip()
cpu_usage = 0.0
# 优化:vmstat 1 2 需要2秒,改为读取 /proc/stat 计算 (虽然复杂但快),或者保留但接受
vmstat_ok = self._execute("command -v vmstat") != ""
if vmstat_ok:
# 注意:vmstat 1 2 必须等2秒,这是无法避免的,但为了性能可以接受
out = self._execute("vmstat 1 2", timeout=5)
lines = out.strip().split('\n')
if len(lines) >= 3:
parts = lines[-1].split()
if len(parts) >= 15:
idle = safe_int(parts[14])
cpu_usage = round(100 - idle, 2)
if cpu_usage > 80:
cpu_status = "过高"
elif cpu_usage > 60:
cpu_status = "中等"
else:
cpu_status = "正常"
cpu_top = []
out = self._execute("ps -eo %cpu,pid,user,comm --sort=-%cpu | head -6")
if out:
for line in out.strip().split('\n')[1:]:
parts = line.strip().split(maxsplit=3)
if len(parts) >= 4:
cpu = parts[0]
pid = parts[1]
user = parts[2]
cmd = parts[3]
try:
cpu_val = float(cpu)
if cpu_val > 20:
status = "过高"
elif cpu_val > 10:
status = "偏大"
else:
status = "正常"
except:
status = "未知"
cpu_top.append([f"{cpu}%", pid, user, cmd[:30], status])
mem_total = "未知"
mem_used = "未知"
mem_free = "未知"
mem_available = "未知"
mem_used_percent = 0.0
out = self._execute("free -h")
if out:
for line in out.strip().split('\n'):
if line.startswith('Mem:'):
parts = line.split()
if len(parts) >= 7:
mem_total = parts[1]
mem_used = parts[2]
mem_free = parts[3]
mem_available = parts[6]
out = self._execute("free | grep Mem | awk '{printf \"%.2f\", $3/$2*100}'")
if out:
try:
mem_used_percent = float(out)
except:
pass
if mem_used_percent > 80:
mem_status = "过高"
elif mem_used_percent > 60:
mem_status = "中等"
else:
mem_status = "正常"
mem_top = []
out = self._execute("ps -eo %mem,rss,pid,user,comm --sort=-%mem | head -6")
if out:
for line in out.strip().split('\n')[1:]:
parts = line.strip().split(maxsplit=4)
if len(parts) >= 5:
mem_per = parts[0]
rss_kb = parts[1]
pid = parts[2]
user = parts[3]
cmd = parts[4]
try:
mem_val = float(mem_per)
if mem_val > 10:
status = "过高"
elif mem_val > 5:
status = "偏大"
else:
status = "正常"
except:
status = "未知"
mem_top.append([f"{mem_per}%", f"{rss_kb}K", pid, user, cmd[:30], status])
disk_usage = []
out = self._execute("df -h | grep -vE 'tmpfs|loop|udev'")
if out:
for line in out.strip().split('\n')[1:]:
parts = line.split()
if len(parts) >= 6:
fs = parts[0]
size = parts[1]
used = parts[2]
avail = parts[3]
use_per = parts[4]
mount = parts[5]
try:
use_val = int(use_per.strip('%'))
if use_val > 80:
status = "危险"
elif use_val > 60:
status = "警告"
else:
status = "正常"
except:
status = "未知"
disk_usage.append([fs, size, used, avail, use_per, mount, status])
self.results["CPU性能"] = {
"columns": ["项目", "值", "状态"],
"data": [
["CPU型号", cpu_model, "已识别"],
["CPU核心", f"{self.cpu_cores} 核心", "已配置"],
["CPU使用率", f"{cpu_usage}%", cpu_status]
]
}
self.results["CPU占用TOP5"] = {"columns": ["CPU%", "PID", "用户", "命令", "状态"], "data": cpu_top}
self.results["内存性能"] = {
"columns": ["项目", "值", "状态"],
"data": [
["总内存", mem_total, "已识别"],
["已使用", f"{mem_used} ({mem_used_percent}%)", mem_status],
["空闲内存", mem_free, "可用"],
["可用内存", mem_available, "可分配"]
]
}
self.results["内存占用TOP5"] = {
"columns": ["内存%", "内存大小", "PID", "用户", "命令", "状态"],
"data": mem_top
}
self.results["磁盘使用率"] = {
"columns": ["文件系统", "大小", "已用", "可用", "使用%", "挂载点", "状态"],
"data": disk_usage
}
# ---------- 9. 服务与系统更新 (核心优化区) ----------
def check_services_updates(self):
critical_services = ["sshd", "firewalld", "crond", "rsyslog", "docker", "nginx", "mysql", "redis"]
services_status = []
has_systemctl = self._execute("command -v systemctl") != ""
for svc in critical_services:
if has_systemctl:
# 优化:使用 is-active 并加上短超时
out = self._execute(f"systemctl is-active --quiet {svc}", timeout=5)
if out == "":
services_status.append([svc, "正常运行", "正常"])
else:
# 不再检查是否 installed,减少命令
services_status.append([svc, "未运行/未安装", "信息"])
else:
out = self._execute(f"service {svc} status", timeout=5)
if "running" in out:
services_status.append([svc, "正常运行", "正常"])
else:
services_status.append([svc, "未知状态", "警告"])
# 【核心修复】系统更新检查优化
updates_info = []
if self._execute("command -v apt", timeout=5) != "":
# 简单检查:不实际 update,只检查是否有 apt
updates_info = [["apt", "检查跳过", "检查跳过", "为避免卡顿已跳过"]]
elif self._execute("command -v yum", timeout=5) != "":
# 【核心修复】移除 yum check-update -q,改为仅检查 yum 可用性
# 因为 yum check-update 极易造成卡死
updates_info = [["yum", "检查跳过", "检查跳过", "为避免卡顿已跳过"]]
else:
updates_info = [["未知包管理器", 0, 0, "无法检测"]]
self.results["关键服务状态"] = {"columns": ["服务", "状态", "评估"], "data": services_status}
self.results["系统更新检查"] = {"columns": ["包管理器", "可用更新", "安全更新", "状态"], "data": updates_info}
# ---------- 10. 日志与定时任务 ----------
def check_logs_cron(self):
error_logs = []
log_files = ["/var/log/messages", "/var/log/syslog"]
for logf in log_files:
# 优化:grep 加上超时
out = self._execute(f"grep -iE 'error|fail|critical|alert|emergency' {logf} 2>/dev/null | grep -v 'CRON' | tail -5", timeout=10)
if out:
for line in out.strip().split('\n')[:5]:
if line:
error_logs.append([logf, clean_string(line[:100])])
login_fails = []
auth_files = ["/var/log/secure", "/var/log/auth.log"]
for af in auth_files:
out = self._execute(f"grep 'Failed password' {af} 2>/dev/null | tail -5", timeout=10)
if out:
for line in out.strip().split('\n')[:5]:
if line:
login_fails.append([af, clean_string(line[:100])])
cron_tasks = []
out = self._execute("cat /etc/crontab 2>/dev/null")
if out:
valid_lines = []
for line in out.strip().split('\n'):
line = line.strip()
if not line or line.startswith('#'):
continue
if line.startswith('SHELL=') or line.startswith('PATH=') or line.startswith('MAILTO='):
continue
valid_lines.append(line)
if valid_lines:
cron_tasks.append(["系统crontab", "\n".join(valid_lines)[:200]])
# 优化:只检查 root 用户的 crontab,不再遍历前5个用户,减少 SSH 交互
out = self._execute("crontab -l -u root 2>/dev/null")
if out and "no crontab" not in out.lower():