-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebui.py
More file actions
960 lines (841 loc) · 39.2 KB
/
Copy pathwebui.py
File metadata and controls
960 lines (841 loc) · 39.2 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
#!/usr/bin/env python3
"""
python_test_waf WebUI
基于 Flask 框架实现的图形化交互界面
"""
from flask import Flask, render_template, request, jsonify, send_file
import os
import sys
import subprocess
import threading
import time
import queue
app = Flask(__name__)
# 测试结果队列
result_queue = queue.Queue()
# 测试状态
is_testing = False
# 当前测试进程
current_process = None
# 测试日志
test_logs = []
# 支持的样本目录列表 - 包含有.black或.white文件的目录,支持2级目录
def get_valid_sample_dirs():
"""获取有效的样本目录,支持2级目录,只有包含.black或.white文件的目录才会被识别"""
valid_dirs = []
# 检查1级目录
for d in os.listdir('.'):
dir_path = os.path.join('.', d)
if os.path.isdir(dir_path) and d != '__pycache__':
# 检查目录中是否存在以.black或.white结尾的文件
has_black = False
has_white = False
try:
for f in os.listdir(dir_path):
if f.endswith('.black'):
has_black = True
elif f.endswith('.white'):
has_white = True
if has_black and has_white:
break
except PermissionError:
# 跳过没有权限访问的目录
continue
if has_black or has_white:
valid_dirs.append(d)
else:
# 检查2级目录
for sub_d in os.listdir(dir_path):
sub_dir_path = os.path.join(dir_path, sub_d)
if os.path.isdir(sub_dir_path):
sub_has_black = False
sub_has_white = False
try:
for f in os.listdir(sub_dir_path):
if f.endswith('.black'):
sub_has_black = True
elif f.endswith('.white'):
sub_has_white = True
if sub_has_black and sub_has_white:
break
except PermissionError:
# 跳过没有权限访问的目录
continue
if sub_has_black or sub_has_white:
valid_dirs.append(os.path.join(d, sub_d))
return valid_dirs
SAMPLE_DIRS = get_valid_sample_dirs()
@app.route('/')
def index():
return render_template('index.html', sample_dirs=SAMPLE_DIRS)
@app.route('/start_test', methods=['POST'])
def start_test():
global is_testing, current_process, test_logs
if is_testing:
return jsonify({'status': 'error', 'message': '测试正在进行中,请稍后再试'})
# 获取表单数据
sample_dir = request.form.get('sample_dir', '1').strip()
target_url = request.form.get('target_url', '').strip()
threads = request.form.get('threads', '10').strip()
timeout = request.form.get('timeout', '10,30').strip()
max_retries = request.form.get('max_retries', '3').strip()
custom_code = request.form.get('custom_code', '403').strip()
rst_detect = request.form.get('rst_detect', 'off').strip()
keyword = request.form.get('keyword', '').strip()
debug = request.form.get('debug', 'off').strip()
output_csv = request.form.get('output_csv', 'off').strip()
csv_path = request.form.get('csv_path', '').strip()
output_samples = request.form.get('output_samples', 'off').strip()
samples_path = request.form.get('samples_path', '').strip()
# 构建命令
cmd = [sys.executable, 'waf_tester.py', '-d', sample_dir]
if target_url:
cmd.extend(['-t', target_url])
cmd.extend(['--threads', threads])
cmd.extend(['--timeout', timeout])
cmd.extend(['--max-retries', max_retries])
cmd.extend(['-C', custom_code])
if rst_detect == 'on':
cmd.append('-R')
if keyword:
cmd.extend(['-K', keyword])
if debug == 'on':
cmd.append('--debug')
# 处理输出CSV结果
if output_csv == 'on' and csv_path:
# 确保路径前缀为tmp/
if not csv_path.startswith('tmp/'):
csv_path = f'tmp/{csv_path}'
cmd.extend(['--output', csv_path])
# 处理输出样本目录
if output_samples == 'on' and samples_path:
# 确保路径前缀为tmp/
if not samples_path.startswith('tmp/'):
samples_path = f'tmp/{samples_path}'
cmd.extend(['--split', samples_path])
# 创建tmp目录(如果不存在)
os.makedirs('tmp', exist_ok=True)
# 清空之前的日志
test_logs = []
def run_test():
global is_testing, current_process
is_testing = True
try:
# 打印后台调度的命令行参数
cmd_str = ' '.join([f"'{arg}'" if ' ' in arg or '"' in arg else arg for arg in cmd])
print(f"\n执行扫描任务:{cmd_str}\n")
print(f"执行命令列表: {cmd}") # 额外打印命令列表便于调试
# 启动测试进程 - 使用shell=False更安全
current_process = subprocess.Popen(
cmd, # cmd已经是列表格式,直接使用
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True,
bufsize=1,
universal_newlines=True,
shell=False
)
# 读取输出 - 使用更可靠的方式确保实时读取,支持进度条同一行显示
if current_process.stdout:
buffer = "" # 用于存储未处理的输出
last_progress_sent = 0 # 记录上次发送进度条的时间
progress_update_interval = 1.0 # 进度条更新间隔(秒)
current_progress = 0 # 当前进度百分比
min_progress_change = 5 # 最小进度变化百分比
while is_testing and current_process.poll() is None:
try:
# 读取部分输出
chunk = current_process.stdout.read(1024)
if chunk:
# 由于设置了text=True,chunk已经是字符串,不需要再decode
buffer += chunk
# 处理缓冲区中的内容
while '\n' in buffer:
line, buffer = buffer.split('\n', 1)
line = line.strip()
if line:
# 检查是否是进度条行
if line.startswith('测试中: ['):
# 解析进度百分比和计数信息
import re
# 提取百分比 (例如: " 60.0%")
progress_match = re.search(r'([0-9.]+)%', line)
# 提取当前计数 (例如: "( 20/")
current_match = re.search(r'\((\s*\d+)/', line)
# 提取总计数 (例如: "/ 50)")
total_match = re.search(r'/\s*(\d+)\)', line)
if progress_match and current_match and total_match:
try:
progress = float(progress_match.group(1))
current = int(current_match.group(1).strip())
total = int(total_match.group(1).strip())
# 只在进度变化超过阈值时发送更新
if abs(progress - current_progress) >= min_progress_change:
# 发送进度更新,使用专门的消息类型
result_queue.put({
'type': 'progress',
'data': {
'percentage': progress,
'current': current,
'total': total
}
})
current_progress = progress
except (ValueError, AttributeError):
# 如果解析失败,跳过这条进度信息
continue
# 不将进度条行添加到普通日志中
else:
# 普通日志,添加到日志列表
test_logs.append(line)
result_queue.put({'type': 'log', 'data': line})
# 处理带有\r的进度条输出
if '\r' in buffer:
# 只保留\r后的内容,作为最新的进度条
buffer = buffer.split('\r')[-1]
if buffer.strip() and buffer.strip().startswith('测试中: ['):
# 解析进度百分比和计数信息
import re
line = buffer.strip()
# 提取百分比
progress_match = re.search(r'([0-9.]+)%', line)
# 提取当前计数
current_match = re.search(r'\((\s*\d+)/', line)
# 提取总计数
total_match = re.search(r'/\s*(\d+)\)', line)
if progress_match and current_match and total_match:
try:
progress = float(progress_match.group(1))
current = int(current_match.group(1).strip())
total = int(total_match.group(1).strip())
current_time = time.time()
# 控制进度条发送频率和变化阈值
if (current_time - last_progress_sent >= progress_update_interval and
abs(progress - current_progress) >= min_progress_change):
# 发送进度更新,使用专门的消息类型
result_queue.put({
'type': 'progress',
'data': {
'percentage': progress,
'current': current,
'total': total
}
})
current_progress = progress
last_progress_sent = current_time
except (ValueError, AttributeError):
# 如果解析失败,跳过这条进度信息
continue
else:
# 防止无输出时的死循环
time.sleep(0.1)
except Exception as e:
error_message = f"读取输出时出错: {str(e)}"
result_queue.put({'type': 'error', 'data': error_message})
test_logs.append(error_message)
print(error_message)
break
# 读取剩余输出
try:
# 处理缓冲区中剩余的内容
if buffer:
buffer = buffer.strip()
if buffer:
test_logs.append(buffer)
result_queue.put({'type': 'log', 'data': buffer})
# 读取剩余的完整行
for line in current_process.stdout:
line = line.strip()
if line:
test_logs.append(line)
result_queue.put({'type': 'log', 'data': line})
except Exception as e:
print(f"读取剩余输出时出错: {str(e)}")
# 等待进程结束
if current_process:
current_process.wait()
# 发送测试完成信号
result_queue.put({'type': 'complete', 'data': f'测试完成,退出码:{current_process.returncode}'})
except Exception as e:
result_queue.put({'type': 'error', 'data': f'测试出错:{str(e)}'})
finally:
is_testing = False
current_process = None
# 启动测试线程
threading.Thread(target=run_test, daemon=True).start()
return jsonify({'status': 'success', 'message': '测试已开始'})
@app.route('/get_results')
def get_results():
"""获取测试结果"""
results = []
while not result_queue.empty():
results.append(result_queue.get())
return jsonify({'results': results})
@app.route('/stop_test')
def stop_test():
"""停止测试"""
global is_testing, current_process
if is_testing and current_process:
current_process.terminate()
is_testing = False
current_process = None
return jsonify({'status': 'success', 'message': '测试已停止'})
else:
return jsonify({'status': 'error', 'message': '没有正在进行的测试'})
@app.route('/get_sample_dirs')
def get_sample_dirs():
"""获取可用的样本目录"""
global SAMPLE_DIRS
SAMPLE_DIRS = get_valid_sample_dirs()
return jsonify({'sample_dirs': SAMPLE_DIRS})
@app.route('/download_file/<path:filename>')
def download_file(filename):
"""提供文件下载功能"""
return send_file(filename, as_attachment=True)
if __name__ == '__main__':
# 创建 templates 目录
os.makedirs('templates', exist_ok=True)
# 创建 index.html 模板文件
index_html = '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>python_test_waf</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
color: #333;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
h1 {
text-align: center;
margin-bottom: 30px;
color: #2c3e50;
}
.form-section {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
margin-bottom: 20px;
}
.form-row {
display: flex;
flex-wrap: wrap;
gap: 20px;
margin-bottom: 15px;
}
.form-group {
flex: 1;
min-width: 200px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
input[type="text"], input[type="number"], select {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
input[type="checkbox"] {
margin-right: 5px;
}
.checkbox-group {
display: flex;
align-items: center;
}
.btn {
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
font-weight: bold;
margin-right: 10px;
}
.btn-primary {
background-color: #3498db;
color: white;
}
.btn-primary:hover {
background-color: #2980b9;
}
.btn-danger {
background-color: #e74c3c;
color: white;
}
.btn-danger:hover {
background-color: #c0392b;
}
.results-section {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
.logs {
background-color: #f8f9fa;
padding: 15px;
border-radius: 4px;
max-height: 500px;
overflow-y: auto;
font-family: monospace;
font-size: 14px;
line-height: 1.5;
border: 1px solid #ddd;
}
.log-line {
margin-bottom: 5px;
}
.log-line:nth-child(odd) {
background-color: #e9ecef;
}
.status {
margin-bottom: 15px;
font-weight: bold;
}
.status.running {
color: #e67e22;
}
.status.idle {
color: #27ae60;
}
.status.error {
color: #e74c3c;
}
@media (max-width: 768px) {
.form-row {
flex-direction: column;
}
.form-group {
min-width: 100%;
}
}
</style>
</head>
<body>
<div class="container">
<h1>python_test_waf</h1>
<div class="form-section">
<h2>测试参数设置</h2>
<form id="test-form">
<div class="form-row">
<div class="form-group">
<label for="sample_dir">样本目录</label>
<select id="sample_dir" name="sample_dir">
{% for dir in sample_dirs %}
<option value="{{ dir }}">{{ dir }}</option>
{% endfor %}
</select>
</div>
<div class="form-group">
<label for="target_url">靶机地址</label>
<input type="text" id="target_url" name="target_url" placeholder="http://127.0.0.1" value="http://127.0.0.1">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="threads">并发线程数</label>
<input type="number" id="threads" name="threads" value="10" min="1" max="100">
</div>
<div class="form-group">
<label for="timeout">超时设置 (连接超时,读取超时 秒)</label>
<input type="text" id="timeout" name="timeout" value="10,30" placeholder="10,30">
</div>
<div class="form-group">
<label for="max_retries">最大重传次数</label>
<input type="number" id="max_retries" name="max_retries" value="3" min="1" max="10">
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="custom_code">自定义 WAF 拦截状态码</label>
<input type="number" id="custom_code" name="custom_code" value="403" min="100" max="599">
</div>
<div class="form-group">
<label for="keyword">响应关键字</label>
<input type="text" id="keyword" name="keyword" placeholder="Forbidden">
</div>
</div>
<div class="form-row">
<div class="form-group checkbox-group">
<input type="checkbox" id="rst_detect" name="rst_detect">
<label for="rst_detect">检测 RST 拦截</label>
</div>
<div class="form-group checkbox-group">
<input type="checkbox" id="debug" name="debug">
<label for="debug">启用调试模式</label>
</div>
</div>
<div class="form-row">
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="output_csv" name="output_csv">
<label for="output_csv">输出 CSV 结果</label>
</div>
<input type="text" id="csv_path" name="csv_path" placeholder="tmp/results.csv" style="margin-top: 5px; display: none;">
</div>
<div class="form-group">
<div class="checkbox-group">
<input type="checkbox" id="output_samples" name="output_samples">
<label for="output_samples">输出样本目录</label>
</div>
<input type="text" id="samples_path" name="samples_path" placeholder="tmp/test_results" value="tmp/test_results" style="margin-top: 5px; display: none;">
</div>
</div>
<div style="display: flex; align-items: center; gap: 10px; flex-wrap: wrap;">
<button type="button" class="btn btn-primary" id="start-btn">开始测试</button>
<button type="button" class="btn btn-danger" id="stop-btn">停止测试</button>
<span id="status" class="status idle">就绪</span>
<div id="results-links" style="margin-left: auto;"></div>
</div>
</form>
</div>
<div class="results-section">
<h2>测试结果</h2>
<!-- 进度条显示 -->
<div id="progress-section" style="margin-bottom: 20px; background-color: white; padding: 20px; border-radius: 8px; border: 1px solid #ddd;">
<h3 style="margin-bottom: 15px;">测试进度</h3>
<div style="display: flex; flex-direction: column; gap: 10px;">
<div style="display: flex; align-items: center; gap: 10px;">
<div style="width: 100%;">
<progress id="progress-bar" value="0" max="100" style="width: 100%; height: 20px; border-radius: 10px; background: #f0f0f0; overflow: hidden;"></progress>
<style>
/* 自定义进度条样式 */
#progress-bar::-webkit-progress-bar {
background-color: #f0f0f0;
border-radius: 10px;
}
#progress-bar::-webkit-progress-value {
background: linear-gradient(90deg, #4CAF50 0%, #45a049 100%);
border-radius: 10px;
transition: width 0.3s ease;
}
#progress-bar::-moz-progress-bar {
background: linear-gradient(90deg, #4CAF50 0%, #45a049 100%);
border-radius: 10px;
}
</style>
</div>
<div id="progress-percentage" style="width: 60px; text-align: right; font-weight: bold;">0.0%</div>
</div>
<div id="progress-info" style="font-size: 14px; color: #666;">准备开始...</div>
</div>
</div>
<!-- 日志显示 -->
<div id="logs" class="logs"></div>
</div>
</div>
<script>
let isTesting = false;
let logInterval = null;
// 更新状态显示
function updateStatus(status) {
const statusEl = document.getElementById('status');
statusEl.className = `status ${status}`;
switch(status) {
case 'running':
statusEl.textContent = '测试进行中...';
break;
case 'idle':
statusEl.textContent = '就绪';
break;
case 'error':
statusEl.textContent = '错误';
break;
}
}
// 开始测试函数
function startTest() {
if (isTesting) return;
// 处理表单数据,确保复选框的值正确
const form = document.getElementById('test-form');
const data = {};
// 处理所有输入字段
const allInputs = form.querySelectorAll('input, select');
allInputs.forEach(input => {
if (input.type === 'checkbox') {
data[input.name] = input.checked ? 'on' : 'off';
} else {
data[input.name] = input.value;
}
});
// 检查必填项
if (!data.target_url) {
alert('请输入靶机地址');
return;
}
// 清空日志和结果链接
document.getElementById('logs').innerHTML = '';
document.getElementById('results-links').innerHTML = '';
// 开始测试
fetch('/start_test', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams(data)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
if (data.status === 'success') {
isTesting = true;
updateStatus('running');
// 开始轮询获取日志,调整为2秒一次以减少资源浪费
if (!logInterval) {
logInterval = setInterval(fetchResults, 2000); // 调整为2秒一次,减少服务器压力
}
} else {
alert(data.message);
}
})
.catch(error => {
console.error('Error:', error);
alert('测试启动失败: ' + error.message);
});
}
// 停止测试函数
function stopTest() {
fetch('/stop_test')
.then(response => response.json())
.then(data => {
alert(data.message);
isTesting = false;
updateStatus('idle');
if (logInterval) {
clearInterval(logInterval);
logInterval = null;
}
})
.catch(error => {
console.error('Error:', error);
});
}
// 带超时的fetch函数
function fetchWithTimeout(url, options = {}, timeout = 10000) {
return Promise.race([
fetch(url, options),
new Promise((_, reject) =>
setTimeout(() => reject(new Error('请求超时')), timeout)
)
]);
}
// 获取测试结果
function fetchResults() {
fetchWithTimeout('/get_results', {}, 15000) // 添加15秒超时
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.json();
})
.then(data => {
const logsEl = document.getElementById('logs');
// 处理结果
data.results.forEach(result => {
switch(result.type) {
case 'progress':
// 处理进度更新
const progressData = result.data;
const progressBar = document.getElementById('progress-bar');
const progressPercentage = document.getElementById('progress-percentage');
const progressInfo = document.getElementById('progress-info');
// 更新进度条
progressBar.value = progressData.percentage;
progressPercentage.textContent = `${progressData.percentage.toFixed(1)}%`;
progressInfo.textContent = `正在测试: ${progressData.current}/${progressData.total} 个样本`;
break;
case 'log':
// 普通日志,创建新行
const logLine = document.createElement('div');
logLine.className = 'log-line';
logLine.textContent = result.data;
logsEl.appendChild(logLine);
// 滚动到底部
logsEl.scrollTop = logsEl.scrollHeight;
break;
case 'complete':
case 'error':
isTesting = false;
updateStatus('idle');
if (logInterval) {
clearInterval(logInterval);
logInterval = null;
}
// 测试完成,更新进度条到100%
const progressBarComplete = document.getElementById('progress-bar');
const progressPercentageComplete = document.getElementById('progress-percentage');
const progressInfoComplete = document.getElementById('progress-info');
progressBarComplete.value = 100;
progressPercentageComplete.textContent = '100.0%';
progressInfoComplete.textContent = '测试完成!';
// 显示结果链接
displayResultsLinks();
// 测试完成后自动关闭输出复选框
document.getElementById('output_csv').checked = false;
document.getElementById('output_samples').checked = false;
// 隐藏对应的输入框
document.getElementById('csv_path').style.display = 'none';
document.getElementById('samples_path').style.display = 'none';
// 测试完成后刷新样本目录列表
refreshSampleDirs();
break;
}
});
})
.catch(error => {
console.error('Error:', error);
});
}
// 显示结果链接
function displayResultsLinks() {
const resultsLinksEl = document.getElementById('results-links');
resultsLinksEl.innerHTML = '';
// 检查是否有CSV文件生成
const csvPath = document.getElementById('csv_path').value;
if (document.getElementById('output_csv').checked && csvPath) {
const csvLink = document.createElement('a');
csvLink.href = `/download_file/${encodeURIComponent(csvPath)}`;
csvLink.textContent = `下载 CSV 结果 (${csvPath})`;
csvLink.className = 'btn btn-primary';
csvLink.style.marginRight = '10px';
csvLink.style.marginBottom = '10px';
resultsLinksEl.appendChild(csvLink);
}
// 检查是否有样本目录生成
const samplesPath = document.getElementById('samples_path').value;
if (document.getElementById('output_samples').checked && samplesPath) {
const samplesLink = document.createElement('a');
samplesLink.href = `javascript:void(0);`;
samplesLink.textContent = `查看样本目录 (${samplesPath})`;
samplesLink.className = 'btn btn-secondary';
samplesLink.style.marginRight = '10px';
samplesLink.style.marginBottom = '10px';
samplesLink.onclick = function() {
alert(`样本目录已生成在: ${samplesPath}\n您可以在服务器上查看该目录`);
};
resultsLinksEl.appendChild(samplesLink);
}
}
// 定期刷新样本目录列表
function refreshSampleDirs() {
fetch('/get_sample_dirs')
.then(response => response.json())
.then(data => {
const selectEl = document.getElementById('sample_dir');
const currentValue = selectEl.value;
selectEl.innerHTML = '';
data.sample_dirs.forEach(dir => {
const option = document.createElement('option');
option.value = dir;
option.textContent = dir;
if (dir === currentValue) {
option.selected = true;
}
selectEl.appendChild(option);
});
})
.catch(error => {
console.error('Error:', error);
});
}
// 生成带时间戳的文件名
function generateTimestamp() {
const now = new Date();
const year = now.getFullYear();
const month = String(now.getMonth() + 1).padStart(2, '0');
const day = String(now.getDate()).padStart(2, '0');
const hour = String(now.getHours()).padStart(2, '0');
const minute = String(now.getMinutes()).padStart(2, '0');
const second = String(now.getSeconds()).padStart(2, '0');
return `${year}${month}${day}_${hour}${minute}${second}`;
}
// 更新带时间戳的默认值
function updateTimestampDefaults() {
const timestamp = generateTimestamp();
document.getElementById('csv_path').value = `tmp/results_${timestamp}.csv`;
document.getElementById('samples_path').value = `tmp/test_results_${timestamp}`;
}
// 处理复选框显示/隐藏逻辑
function setupCheckboxHandlers() {
// 输出CSV结果复选框
const outputCsvCheckbox = document.getElementById('output_csv');
const csvPathInput = document.getElementById('csv_path');
outputCsvCheckbox.addEventListener('change', function() {
csvPathInput.style.display = this.checked ? 'block' : 'none';
if (this.checked) {
// 每次勾选时,更新文件名
const timestamp = generateTimestamp();
csvPathInput.value = `tmp/results_${timestamp}.csv`;
}
});
// 输出样本目录复选框
const outputSamplesCheckbox = document.getElementById('output_samples');
const samplesPathInput = document.getElementById('samples_path');
outputSamplesCheckbox.addEventListener('change', function() {
samplesPathInput.style.display = this.checked ? 'block' : 'none';
if (this.checked) {
// 每次勾选时,更新文件名
const timestamp = generateTimestamp();
samplesPathInput.value = `tmp/test_results_${timestamp}`;
}
});
}
// 初始化
window.onload = function() {
// 绑定按钮事件
const startBtn = document.getElementById('start-btn');
const stopBtn = document.getElementById('stop-btn');
if (startBtn) {
startBtn.addEventListener('click', startTest);
console.log('开始测试按钮事件绑定成功');
} else {
console.error('开始测试按钮未找到!');
}
if (stopBtn) {
stopBtn.addEventListener('click', stopTest);
console.log('停止测试按钮事件绑定成功');
} else {
console.error('停止测试按钮未找到!');
}
refreshSampleDirs();
setupCheckboxHandlers();
// 初始生成带时间戳的默认值
updateTimestampDefaults();
};
</script>
</body>
</html>
'''
# 写入模板文件
os.makedirs('templates', exist_ok=True)
with open('templates/index.html', 'w', encoding='utf-8') as f:
f.write(index_html)
print("WebUI 已创建完成!")
print("使用以下命令启动 WebUI:")
print(f"python3 {os.path.basename(__file__)}")
print("然后在浏览器中访问:http://localhost:5001")
# 启动 Flask 应用 - 配置为处理并发请求
app.run(debug=True, host='0.0.0.0', port=5001, threaded=True)