forked from mrsee239108/KY-ops
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
3340 lines (2909 loc) · 128 KB
/
Copy pathapp.py
File metadata and controls
3340 lines (2909 loc) · 128 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
import threading
from extuner import common
from flask import Flask, render_template, jsonify, request, send_file, make_response, Response
from collections import deque
import psutil
import platform
import socket
import subprocess
import os
import json
import time
import shutil
import re
from datetime import datetime, timedelta
import requests
from pathlib import Path
# 导入AI服务
from ai_service import ai_service
from security_scanner import start_new_scan, get_specified_scan_status, SecurityScanner
app = Flask(__name__)
# 配置
app.config['SECRET_KEY'] = 'your-secret-key-here'
# 初始化实时CPU监控
try:
from extuner.category.get_cpu_info import RealTimeCPU
from extuner.common.global_call import GlobalCall
real_time_cpu_monitor = RealTimeCPU(interval=2)
real_time_cpu_monitor.start_broadcasting()
print("CPU实时监控已启动")
except ImportError as e:
print(f"无法导入实时CPU监控: {e}")
real_time_cpu_monitor = None
except Exception as e:
print(f"启动实时CPU监控失败: {e}")
real_time_cpu_monitor = None
# 初始化实时内存监控
try:
from extuner.category.get_memory_info import RealTimeMemory
from extuner.common.global_call import GlobalCall
real_time_memory_monitor = RealTimeMemory(interval=2)
real_time_memory_monitor.start_broadcasting()
print("内存实时监控已启动")
except ImportError as e:
print(f"无法导入实时内存监控: {e}")
real_time_memory_monitor = None
except Exception as e:
print(f"启动实时内存监控失败: {e}")
real_time_memory_monitor = None
# 初始化实时网络监控
try:
from extuner.category.get_net_info import RealTimeNet
from extuner.common.global_call import GlobalCall
real_time_net_monitor = RealTimeNet(interval=2)
real_time_net_monitor.start_broadcasting()
print("网络实时监控已启动")
except ImportError as e:
print(f"无法导入实时网络监控: {e}")
real_time_net_monitor = None
except Exception as e:
print(f"启动实时网络监控失败: {e}")
real_time_net_monitor = None
# 初始化实时磁盘监控
try:
from extuner.category.get_disk_info import RealTimeDisk
from extuner.common.global_call import GlobalCall
real_time_disk_monitor = RealTimeDisk(interval=2)
real_time_disk_monitor.start_broadcasting()
print("磁盘实时监控已启动")
except ImportError as e:
print(f"无法导入实时磁盘监控: {e}")
real_time_disk_monitor = None
except Exception as e:
print(f"启动实时磁盘监控失败: {e}")
real_time_disk_monitor = None
try:
from extuner.category.get_system_message import RealTimeSysMessage
from extuner.common.global_call import GlobalCall
real_time_sys_message_monitor = RealTimeSysMessage(interval=2)
real_time_sys_message_monitor.start_broadcasting()
print("系统消息实时监控已启动")
except ImportError as e:
print(f"无法导入系统消息实时监控: {e}")
real_time_sys_message_monitor = None
except Exception as e:
print(f"启动系统消息实时监控失败: {e}")
real_time_sys_message_monitor = None
# 全局日志缓存和计数器
log_cache = deque(maxlen=10000) # 最多缓存10000条日志
log_level_stats = {'info': 0, 'warn': 0, 'error': 0, 'total': 0}
log_cache_lock = threading.Lock() # 线程安全锁
# 添加CORS支持
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Content-Type,Authorization')
response.headers.add('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS')
return response
def get_external_ip():
"""获取外部IP地址"""
try:
response = requests.get('https://api.ipify.org?format=text', timeout=5)
return response.text.strip()
except:
return "获取失败"
def get_internal_ip():
"""获取内部IP地址"""
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except:
return "127.0.0.1"
def format_bytes(bytes_value):
"""格式化字节数"""
if bytes_value == 0:
return "0 B"
units = ['B', 'KB', 'MB', 'GB', 'TB']
unit_index = 0
while bytes_value >= 1024 and unit_index < len(units) - 1:
bytes_value /= 1024
unit_index += 1
return f"{bytes_value:.2f} {units[unit_index]}"
def format_uptime(seconds):
"""格式化运行时间"""
days = seconds // 86400
hours = (seconds % 86400) // 3600
minutes = (seconds % 3600) // 60
if days > 0:
return f"{days}天 {hours}小时 {minutes}分钟"
elif hours > 0:
return f"{hours}小时 {minutes}分钟"
else:
return f"{minutes}分钟"
def parse_extune_data():
"""解析extune输出的数据文件"""
extune_data_path = os.path.join(os.path.dirname(__file__), 'extuner', 'extunerData')
result = {
'hostname': '未知',
'system_name': '未知',
'kernel_version': '未知',
'external_ip': '获取失败',
'internal_ip': '未知',
'cpu_model': '未知',
'cpu_architecture': '未知',
'cpu_count': 0,
'memory_total': '未知',
'memory_free': '未知',
'disk_total': '未知',
'disk_info': '未知',
'network_info': '未知',
'os_version': '未知',
'gcc_version': '未知',
'glibc_version': '未知',
'jdk_version': '未知',
'uptime_days': '0 天',
'last_update': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
try:
# 解析CPU信息
cpu_file = os.path.join(extune_data_path, 'CPUInfo.txt')
if os.path.exists(cpu_file):
with open(cpu_file, 'r', encoding='utf-8') as f:
cpu_content = f.read()
# 提取CPU型号
cpu_match = re.search(r'Model name:\s*(.+)', cpu_content)
if cpu_match:
result['cpu_model'] = cpu_match.group(1).strip()
# 提取CPU架构
arch_match = re.search(r'Architecture:\s*(.+)', cpu_content)
if arch_match:
result['cpu_architecture'] = arch_match.group(1).strip()
# 提取CPU核心数
cpu_count_match = re.search(r'CPU\(s\):\s*(\d+)', cpu_content)
if cpu_count_match:
result['cpu_count'] = int(cpu_count_match.group(1))
# 解析内存信息
mem_file = os.path.join(extune_data_path, 'memInfo.txt')
if os.path.exists(mem_file):
with open(mem_file, 'r', encoding='utf-8') as f:
mem_content = f.read()
# 提取总内存
mem_total_match = re.search(r'MemTotal:\s*(\d+)\s*kB', mem_content)
if mem_total_match:
mem_kb = int(mem_total_match.group(1))
mem_bytes = mem_kb * 1024
result['memory_total'] = format_bytes(mem_bytes)
# 提取空闲内存
mem_free_match = re.search(r'MemFree:\s*(\d+)\s*kB', mem_content)
if mem_free_match:
mem_free_kb = int(mem_free_match.group(1))
mem_free_bytes = mem_free_kb * 1024
result['memory_free'] = format_bytes(mem_free_bytes)
# 解析磁盘信息
disk_file = os.path.join(extune_data_path, 'diskInfo.txt')
if os.path.exists(disk_file):
with open(disk_file, 'r', encoding='utf-8') as f:
disk_content = f.read()
# 提取磁盘总容量
disk_match = re.search(r'Disk /dev/sda: ([\d.]+) GiB', disk_content)
if disk_match:
disk_gb = float(disk_match.group(1))
disk_bytes = int(disk_gb * 1024 * 1024 * 1024)
result['disk_total'] = format_bytes(disk_bytes)
result['disk_info'] = f"sda: {disk_gb} GiB"
# 解析网络信息
net_file = os.path.join(extune_data_path, 'netInfo.txt')
if os.path.exists(net_file):
with open(net_file, 'r', encoding='utf-8') as f:
net_content = f.read()
# 提取网络接口信息
interface_match = re.search(r'NAME\s+UUID\s+TYPE\s+DEVICE\s*\n(\w+)', net_content)
if interface_match:
result['network_info'] = interface_match.group(1)
# 提取内部IP(从网络配置中获取)
# 这里需要根据实际的网络配置格式调整
ip_match = re.search(r'inet (192\.168\.\d+\.\d+)', net_content)
if ip_match:
result['internal_ip'] = ip_match.group(1)
# 解析系统参数信息
sys_file = os.path.join(extune_data_path, 'sysParamInfo.txt')
if os.path.exists(sys_file):
with open(sys_file, 'r', encoding='utf-8') as f:
sys_content = f.read()
# 从sysctl输出中提取主机名
hostname_match = re.search(r'kernel\.hostname = (.+)', sys_content)
if hostname_match:
result['hostname'] = hostname_match.group(1).strip()
# 从sysctl输出中提取内核版本
kernel_match = re.search(r'kernel\.osrelease = (.+)', sys_content)
if kernel_match:
result['kernel_version'] = kernel_match.group(1).strip()
# 从sysctl输出中提取操作系统类型
os_match = re.search(r'kernel\.ostype = (.+)', sys_content)
if os_match:
result['system_name'] = os_match.group(1).strip()
# 尝试获取更详细的系统版本信息
kylin_match = re.search(r'kernel\.kylinversion = (.+)', sys_content)
if kylin_match:
result['os_version'] = kylin_match.group(1).strip()
# 解析系统消息以获取GCC版本
sys_msg_file = os.path.join(extune_data_path, 'systemMessage.txt')
if os.path.exists(sys_msg_file):
with open(sys_msg_file, 'r', encoding='utf-8') as f:
sys_msg_content = f.read()
# 提取GCC版本
gcc_match = re.search(r'gcc version ([\d.]+)', sys_msg_content)
if gcc_match:
result['gcc_version'] = gcc_match.group(1)
# 尝试获取Glibc版本(通常需要执行命令)
try:
glibc_result = subprocess.run(['ldd', '--version'], capture_output=True, text=True, timeout=5)
if glibc_result.returncode == 0:
glibc_match = re.search(r'ldd \(GNU libc\) ([\d.]+)', glibc_result.stdout)
if glibc_match:
result['glibc_version'] = glibc_match.group(1)
except:
result['glibc_version'] = '未知'
# 尝试获取JDK版本
try:
java_result = subprocess.run(['java', '-version'], capture_output=True, text=True, timeout=5)
if java_result.returncode == 0:
java_match = re.search(r'version "([^"]+)"', java_result.stderr)
if java_match:
result['jdk_version'] = java_match.group(1)
except:
result['jdk_version'] = '未安装'
# 获取外部IP(实时获取)
result['external_ip'] = get_external_ip()
# 计算运行天数(使用psutil获取)
try:
boot_time = psutil.boot_time()
uptime_seconds = int(time.time() - boot_time)
uptime_days = uptime_seconds // 86400
result['uptime_days'] = f"{uptime_days} 天"
except:
result['uptime_days'] = "0 天"
except Exception as e:
print(f"解析extune数据时出错: {e}")
return result
# 路由定义
@app.route('/')
def desktop():
"""Windows 10 桌面主页"""
return render_template('desktop.html')
@app.route('/system-info')
def system_info():
"""系统信息页面"""
return render_template('system_info.html')
@app.route('/file-manager')
def file_manager():
"""文件管理器页面"""
return render_template('file_manager.html')
@app.route('/task-manager')
def task_manager():
"""任务管理器页面"""
return render_template('task_manager.html')
@app.route('/network-monitor')
def network_monitor():
"""网络监控页面"""
return render_template('network_monitor.html')
@app.route('/performance-monitor')
def performance_monitor():
"""性能监控页面"""
return render_template('performance_monitor.html')
@app.route('/security-center')
def security_center():
"""安全中心页面"""
return render_template('security_center.html')
@app.route('/terminal')
def terminal():
"""终端页面"""
return render_template('terminal.html')
@app.route('/settings')
def settings():
"""设置页面"""
return render_template('settings.html')
@app.route('/ai-chat')
def ai_chat():
"""AI对话页面"""
return render_template('ai_chat.html')
@app.route('/test-js')
def test_js():
"""JavaScript测试页面"""
return render_template('test_js.html')
# API 路由
@app.route('/system_info.json')
def get_system_info_json():
"""提供预生成的系统信息JSON文件"""
try:
json_file_path = os.path.join(os.path.dirname(__file__), 'system_info.json')
if os.path.exists(json_file_path):
return send_file(json_file_path, mimetype='application/json')
else:
# 如果JSON文件不存在,返回404
return jsonify({'error': 'system_info.json文件不存在'}), 404
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/system-status')
def system_status():
"""获取系统状态信息(使用实时CPU数据)"""
try:
# 从全局广播获取CPU数据
cpu_data = GlobalCall.real_time_cpu_data
if not cpu_data:
# 如果实时数据不可用,使用psutil作为后备
cpu_percent = psutil.cpu_percent(interval=1)
cpu_percent_per_core = [psutil.cpu_percent(interval=1, percpu=True)[i] for i in range(psutil.cpu_count())]
cpu_count = psutil.cpu_count()
cpu_name = f"Unknown CPU ({cpu_count} cores)"
load_avg = psutil.getloadavg() if hasattr(psutil, 'getloadavg') else [0, 0, 0]
cpu_freq = psutil.cpu_freq().current if hasattr(psutil, 'cpu_freq') else 0
logical_cpu_count = psutil.cpu_count(logical=True)
usr = 0
nice = 0
sys = 0
iowait = 0
irq = 0
soft = 0
steal = 0
guest = 0
gnice = 0
idle = 0
# 进程信息
processes = []
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent', 'memory_percent']):
try:
proc_info = proc.info
if proc_info['cpu_percent'] > 0 or proc_info['memory_percent'] > 0:
processes.append(proc_info)
except (psutil.NoSuchProcess, psutil.AccessDenied):
continue
# 按CPU使用率排序,取前10个
top_processes = sorted(processes, key=lambda x: x['cpu_percent'] or 0, reverse=True)[:10]
else:
# 使用RealTimeCPU提供的数据
cpu_percent = cpu_data['total_usage']
cpu_percent_per_core = cpu_data['core_usage']
cpu_count = cpu_data['cpu_count']
cpu_name = cpu_data['model_name']
load_avg = cpu_data['load_avg']
cpu_freq = cpu_data['cpu_freq']
logical_cpu_count = cpu_data['logical_cpu_count']
top_processes = cpu_data['top_processes']
usr = cpu_data['usr']
nice = cpu_data['nice']
sys = cpu_data['sys']
iowait = cpu_data['iowait']
irq = cpu_data['irq']
soft = cpu_data['soft']
steal = cpu_data['steal']
guest = cpu_data['guest']
gnice = cpu_data['gnice']
idle = cpu_data['idle']
# 从全局广播获取内存数据
memory_data = GlobalCall.real_time_mem_data
if not memory_data:
# 如果实时内存数据不可用,使用psutil作为后备
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
else:
# 使用RealTimeMemory提供的数据
memory = type('obj', (object,), {
'total': memory_data['mem_total'],
'used': memory_data['mem_used'],
'free': memory_data['mem_free'],
'percent': memory_data['mem_percent'],
'cached': memory_data['mem_cached'],
'buffers': memory_data['mem_buffers']
})()
swap = type('obj', (object,), {
'total': memory_data['swap_total'],
'used': memory_data['swap_used'],
'free': memory_data['swap_free'],
'percent': memory_data['swap_percent']
})()
# 网络详细信息 - 从全局广播获取网络数据
net_data = GlobalCall.real_time_net_data
if not net_data:
# 如果实时网络数据不可用,使用psutil作为后备
net_io = psutil.net_io_counters()
net_interfaces = {}
rx_speed = 0.0
tx_speed = 0.0
else:
# 使用RealTimeNet提供的数据
net_io = net_data.get('net_io', {})
net_interfaces = net_data.get('net_interfaces', {})
rx_speed = net_data.get('total_rx_speed', 0.0)
tx_speed = net_data.get('total_tx_speed', 0.0)
# 从全局广播获取磁盘数据
disk_data = GlobalCall.real_time_disk_data
if not disk_data:
# 如果实时数据不可用,使用psutil作为后备
disk_usage = []
partitions = psutil.disk_partitions()
for partition in partitions:
try:
usage = psutil.disk_usage(partition.mountpoint)
disk_usage.append({
'device': partition.device,
'mountpoint': partition.mountpoint,
'fstype': partition.fstype,
'total': usage.total,
'used': usage.used,
'free': usage.free,
'percent': usage.percent,
'utilization': 0.0
})
except Exception:
continue
disk_io = psutil.disk_io_counters()
disk_io_data = {
'read_bytes': disk_io.read_bytes if disk_io else 0,
'write_bytes': disk_io.write_bytes if disk_io else 0,
'read_count': disk_io.read_count if disk_io else 0,
'write_count': disk_io.write_count if disk_io else 0,
}
total_utilization = psutil.disk_io_counters(perdisk=True)
else:
# 使用RealTimeDisk提供的数据
disk_usage = disk_data['disk_usage']
disk_io_data = disk_data['disk_io']
total_utilization = disk_data['total_utilization']
"""整合数据"""
return jsonify({
'cpu_usage': cpu_percent,
'cpu_percent_per_core': cpu_percent_per_core,
'cpu_model': cpu_name,
'cpu_count': cpu_count,
'cpu_frequency': cpu_freq,
'cpu_details': {
'usr': usr,
'nice': nice,
'sys': sys,
'iowait': iowait,
'irq': irq,
'soft': soft,
'steal': steal,
'guest': guest,
'gnice': gnice,
'idle': idle
},
'logical_cpu_count': logical_cpu_count,
'load_avg': load_avg,
'top_processes': top_processes,
'memory_usage': memory.percent,
'memory_total': { # 内存信息
'memory_percent': memory.percent,
'memory_used': memory.used,
'memory_total': memory.total,
'memory_free': memory.free,
'memory_cached': memory.cached,
'memory_buffers': memory.buffers,
# 交换内存信息
'swap_percent': swap.percent,
'swap_used': swap.used,
'swap_total': swap.total,
'swap_free': swap.free
},
'disk_info': {
'disk_usage': disk_usage,
'disk_io': disk_io_data,
'total_utilization': total_utilization
},
'net_interfaces': net_interfaces,
'net_io': net_io,
'rx_speed': rx_speed,
'tx_speed': tx_speed,
'current_time': datetime.now().strftime('%H:%M'),
'current_date': datetime.now().strftime('%Y/%m/%d'),
'day_of_week': datetime.now().strftime('%A')
})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/system-info-txt')
def get_system_info_txt():
"""从info.txt文件获取系统信息"""
try:
info_file = os.path.join(os.path.dirname(__file__), 'extuner', 'info.txt')
if not os.path.exists(info_file):
return jsonify({
'error': 'info.txt文件不存在',
'message': '请先运行extune数据采集生成info.txt文件'
}), 404
with open(info_file, 'r', encoding='utf-8') as f:
content = f.read()
# 解析txt内容为结构化数据
info_data = parse_info_txt(content)
return jsonify(info_data)
except Exception as e:
return jsonify({'error': str(e)}), 500
def parse_info_txt(content):
"""解析info.txt文件内容为结构化数据"""
lines = content.split('\n')
data = {
'base_info': {},
'cpu_info': {},
'memory_info': {},
'network_info': [],
'disk_info': [],
'time_info': {}
}
current_section = None
current_network = {}
current_disk = {}
for line in lines:
line = line.strip()
if not line:
continue
if line.startswith('=== ') and line.endswith(' ==='):
current_section = line.replace('===', '').strip()
continue
if line == '---':
if current_section == '网络接口信息' and current_network:
data['network_info'].append(current_network.copy())
current_network = {}
elif current_section == '磁盘信息' and current_disk:
data['disk_info'].append(current_disk.copy())
current_disk = {}
continue
if ':' in line:
key, value = line.split(':', 1)
key = key.strip()
value = value.strip()
if current_section == '系统基本信息':
data['base_info'][key] = value
elif current_section == 'CPU信息':
data['cpu_info'][key] = value
elif current_section == '内存信息':
data['memory_info'][key] = value
elif current_section == '网络接口信息':
current_network[key] = value
elif current_section == '磁盘信息':
current_disk[key] = value
elif current_section == '时间信息':
data['time_info'][key] = value
# 处理最后一个网络接口或磁盘
if current_network:
data['network_info'].append(current_network)
if current_disk:
data['disk_info'].append(current_disk)
return data
@app.route('/api/system-info')
def get_system_info():
"""获取详细系统信息"""
try:
# 从extune数据文件获取基本信息
extune_data = parse_extune_data()
# 获取实时性能数据
cpu_percent = psutil.cpu_percent(interval=1)
cpu_freq = psutil.cpu_freq()
memory = psutil.virtual_memory()
swap = psutil.swap_memory()
# 磁盘信息 - Windows环境适配
try:
if os.name == 'nt': # Windows
disk = psutil.disk_usage('C:')
else: # Linux/Unix
disk = psutil.disk_usage('/')
except:
# 如果获取失败,使用默认值
disk = type('obj', (object,), {'total': 0, 'used': 0, 'free': 0})()
network_io = psutil.net_io_counters()
# 运行时间
boot_time = psutil.boot_time()
uptime_seconds = int(time.time() - boot_time)
return jsonify({
# 基本系统信息
'hostname': extune_data['hostname'],
'system_name': extune_data['system_name'],
'kernel_version': extune_data['kernel_version'],
'os_version': extune_data['os_version'],
# CPU信息
'cpu_model': extune_data['cpu_model'],
'cpu_architecture': extune_data['cpu_architecture'],
'cpu_count': extune_data['cpu_count'],
'cpu_usage': cpu_percent,
'cpu_frequency': cpu_freq.current if cpu_freq else 0,
# 内存信息
'memory_total': extune_data['memory_total'],
'memory_free': extune_data['memory_free'],
'memory_total_bytes': memory.total,
'memory_available': memory.available,
'memory_used': memory.used,
'memory_percent': memory.percent,
# Swap内存信息
'swap_total': swap.total,
'swap_used': swap.used,
'swap_free': swap.free,
'swap_percent': swap.percent,
# 磁盘信息
'disk_total': extune_data['disk_total'],
'disk_info': extune_data['disk_info'],
'disk_total_bytes': disk.total,
'disk_used': disk.used,
'disk_free': disk.free,
'disk_percent': (disk.used / disk.total) * 100 if disk.total > 0 else 0,
# 网络信息
'external_ip': extune_data['external_ip'],
'internal_ip': extune_data['internal_ip'],
'network_info': extune_data['network_info'],
'network_bytes_sent': network_io.bytes_sent,
'network_bytes_recv': network_io.bytes_recv,
'network_packets_sent': network_io.packets_sent,
'network_packets_recv': network_io.packets_recv,
# 开发工具版本
'gcc_version': extune_data['gcc_version'],
'glibc_version': extune_data['glibc_version'],
'jdk_version': extune_data['jdk_version'],
# 运行时间信息
'uptime_seconds': uptime_seconds,
'uptime_formatted': format_uptime(uptime_seconds),
'uptime_days': extune_data['uptime_days'],
'last_update': extune_data['last_update'],
'boot_time': datetime.fromtimestamp(boot_time).strftime('%Y-%m-%d %H:%M:%S')
})
except Exception as e:
return jsonify({'error': str(e)}), 500
# 性能报警全局数据结构
performanceAlert = [] # 存储当前活动的报警
alert_history = {} # 存储报警最后触发时间 {alert_code: timestamp}
alert_lock = threading.Lock() # 线程安全锁
# 报警阈值配置
ALERT_THRESHOLDS = {
"cpu-overload": 85.0, # CPU使用率阈值(%)
"memory-overload": 90.0, # 内存使用率阈值(%)
"disk-space-overload": 90.0, # 磁盘空间使用率阈值(%)
"disk-io-overload": 80.0, # 磁盘IO利用率阈值(%)
"network-overload": 80.0, # 网络带宽利用率阈值(%)
"high-process-load": 50.0, # 单个进程CPU占用阈值(%)
}
# 报警清除时间(秒)
ALERT_CLEAR_TIME = 300 # 5分钟内无再次触发则清除
@app.route('/api/check-alert')
def check_alert():
try:
current_time = time.time()
# 1. 清除过期的报警
with alert_lock:
# 移除超过清除时间的报警
performanceAlert[:] = [alert for alert in performanceAlert
if current_time - alert_history.get(alert["alert_code"], 0) <= ALERT_CLEAR_TIME]
# 更新报警历史中过期的条目
for code in list(alert_history.keys()):
if current_time - alert_history[code] > ALERT_CLEAR_TIME:
del alert_history[code]
# 2. 获取实时性能数据
# 使用GlobalCall的实时数据(参考/api/performance-data的实现)
try:
# 获取CPU数据
cpu_data = GlobalCall.real_time_cpu_data
if not cpu_data:
return jsonify(performanceAlert)
# 获取内存数据
memory_data = GlobalCall.real_time_mem_data
if not memory_data:
return jsonify(performanceAlert)
# 获取磁盘数据
disk_data = GlobalCall.real_time_disk_data
if not disk_data:
return jsonify(performanceAlert)
# 获取网络数据
net_data = GlobalCall.real_time_net_data
if not net_data:
return jsonify(performanceAlert)
except Exception as e:
print(f"获取性能数据失败: {e}")
return jsonify(performanceAlert)
# 3. 检查各项阈值
with alert_lock:
# 检查CPU负载
if cpu_data['total_usage'] > ALERT_THRESHOLDS["cpu-overload"]:
update_alert("cpu-overload",
f"CPU使用率过高: {cpu_data['total_usage']:.2f}%",
current_time)
# 检查内存使用
if memory_data['mem_percent'] > ALERT_THRESHOLDS["memory-overload"]:
update_alert("memory-overload",
f"内存使用率过高: {memory_data['mem_percent']:.2f}%",
current_time)
# 检查磁盘空间
for partition in disk_data['disk_usage']:
if partition['percent'] > ALERT_THRESHOLDS["disk-space-overload"]:
update_alert("disk-space-overload",
f"磁盘 {partition['mountpoint']} 空间不足: {partition['percent']:.2f}%",
current_time)
# 检查磁盘IO
max_io_util = 0.0
for device, stats in disk_data['disk_io'].items():
if 'utilization' in stats and stats['utilization'] > max_io_util:
max_io_util = stats['utilization']
if max_io_util > ALERT_THRESHOLDS["disk-io-overload"]:
update_alert("disk-io-overload",
f"磁盘IO负载过高: {max_io_util:.2f}%",
current_time)
# 检查网络负载
net_util = max(net_data.get('total_rx_speed', 0), net_data.get('total_tx_speed', 0))
if net_util > ALERT_THRESHOLDS["network-overload"]:
update_alert("network-overload",
f"网络负载过高: {(net_util / 1024 /1024):.2f} MB/s",
current_time)
# 检查高负载进程
for proc in cpu_data.get('top_processes', [])[:5]: # 检查前5个高负载进程
if proc.get('cpu_percent', 0) > ALERT_THRESHOLDS["high-process-load"]:
update_alert("high-process-load",
f"进程 {proc.get('command', '未知')} 占用过高CPU: {proc['cpu_percent']}%",
current_time)
return jsonify(performanceAlert)
except Exception as e:
print(f"报警检查错误: {e}")
return jsonify({"error": str(e)}), 500
def update_alert(alert_code, description, timestamp):
"""更新报警状态"""
# 更新报警最后触发时间
alert_history[alert_code] = timestamp
# 检查是否已存在该报警
existing_alert = next((a for a in performanceAlert if a["alert_code"] == alert_code), None)
if existing_alert:
# 更新现有报警
existing_alert["description"] = description
existing_alert["timestamp"] = timestamp
else:
# 创建新报警
new_alert = {
"alert_code": alert_code,
"description": description,
"timestamp": timestamp,
"solution": "" # 初始为空,由AI后续生成
}
performanceAlert.append(new_alert)
@app.route('/api/system-log')
def get_system_log():
try:
system_log = GlobalCall.real_time_sys_message_data
recent_logs = system_log.get('recent_logs', [])
logs_today = []
# 使用锁确保线程安全
with log_cache_lock:
# 只处理新出现的日志
new_logs = [log for log in recent_logs if log not in log_cache]
# 更新缓存
log_cache.extend(new_logs)
logs_today = list(log_cache)
error_logs = system_log['error_logs']
return jsonify({'recent_logs': logs_today, 'error_logs': error_logs})
except Exception as e:
return jsonify({'error': str(e)}), 500
@app.route('/api/security-overview')
def get_security_overview():
"""获取安全概览数据 - 实时获取今日处理日志、今日异常和告警等级"""
try:
# 获取今日日期
system_log = GlobalCall.real_time_sys_message_data
# 初始化计数器
today_logs_count = 0
today_anomalies_count = 0
risk_level = "正常"
# 1. 统计今日处理的日志数量
recent_logs = system_log.get('recent_logs', [])
# 使用锁确保线程安全
with log_cache_lock:
# 只处理新出现的日志
new_logs = [log for log in recent_logs if log not in log_cache]
# 更新缓存
log_cache.extend(new_logs)
# 2. 统计今日异常数量
for log_content in new_logs:
if not log_content or not log_content.strip():
continue
lines = log_content.split('\n')
for line in lines:
line = line.strip()
if not line:
continue
# 更新统计计数
log_level_stats['total'] += 1
line_lower = line.lower()
if any(keyword in line_lower for keyword in ['error', 'err', 'fail', 'critical', 'exception']):
log_level_stats['error'] += 1
elif any(keyword in line_lower for keyword in ['warn', 'warning', 'caution']):
log_level_stats['warn'] += 1
else:
log_level_stats['info'] += 1
today_logs_count = log_level_stats['total']
today_anomalies_count = log_level_stats['error'] + log_level_stats['warn']
# 3. 确定风险等级
if today_anomalies_count >= 10:
risk_level = "高危"
elif today_anomalies_count >= 5:
risk_level = "中等"
elif today_anomalies_count >= 1:
risk_level = "低风险"
else:
risk_level = "正常"
# 4. 获取监控状态
monitor_status = "运行中"
try:
from security_scanner import scan_tasks
active_scans = len([scanner for scanner in scan_tasks.values() if hasattr(scanner, 'status') and scanner.status == 'running'])
if active_scans > 0:
monitor_status = f"运行中 ({active_scans}个扫描任务)"
except:
pass
overview_data = {
'today_logs': today_logs_count,
'today_anomalies': today_anomalies_count,
'risk_level': risk_level,
'monitor_status': monitor_status,
'last_update': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
}
print(f"[DEBUG] 安全概览数据: {overview_data}")