-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjms_reporting.py
More file actions
1643 lines (1483 loc) · 57.5 KB
/
Copy pathjms_reporting.py
File metadata and controls
1643 lines (1483 loc) · 57.5 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
from __future__ import annotations
from collections import Counter
from contextlib import contextmanager, suppress
from datetime import date, datetime, timedelta
from html import escape
import json
import os
from pathlib import Path
import re
import tempfile
from typing import Any
try:
from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
except ImportError: # pragma: no cover
try:
from backports.zoneinfo import ZoneInfo, ZoneInfoNotFoundError # type: ignore[no-redef]
except ImportError: # pragma: no cover
ZoneInfo = None # type: ignore[assignment]
ZoneInfoNotFoundError = None # type: ignore[assignment]
from jms_analytics import (
_extract_account,
_extract_asset,
_extract_datetime,
_extract_direction,
_extract_duration,
_extract_protocol,
_extract_source_ip,
_extract_status,
_extract_user,
_fetch_command_records,
_fetch_file_transfer_records,
_fetch_session_records,
_first_field,
_is_failed_login,
_login_records,
_string_value,
license_detail_query,
parse_date_value,
parse_datetime_value,
resolve_command_storage_context,
suspicious_operation_summary,
)
from jms_runtime import (
CLIError,
GLOBAL_ORG_ID,
build_cli_guidance_payload,
list_accessible_orgs,
parse_bool,
)
JUMPSERVER_API_DIR = Path(__file__).resolve().parent
REPO_ROOT = Path(__file__).resolve().parents[1]
SKILL_DIR = REPO_ROOT
REPORT_TEMPLATE_PATH = REPO_ROOT / "template" / "bastion-daily-usage-template.html"
REPORT_METADATA_PATH = (
REPO_ROOT / "references" / "metadata" / "daily_usage_report_template_fields.json"
)
PLACEHOLDER_RE = re.compile(r"\{\{\s*([a-zA-Z0-9_]+)\s*\}\}")
DATE_COMPACT_RE = re.compile(r"^(?P<year>\d{4})(?P<month>\d{2})(?P<day>\d{2})$")
DATE_CN_RE = re.compile(
r"^(?:(?P<year>\d{4})\s*年)?\s*(?P<month>\d{1,2})\s*月\s*(?P<day>\d{1,2})\s*[日号]$"
)
EMPTY_TEXT = "暂无数据"
if ZoneInfo is None:
SHANGHAI_TZ = None
else:
try:
SHANGHAI_TZ = ZoneInfo("Asia/Shanghai")
except ZoneInfoNotFoundError: # pragma: no cover
SHANGHAI_TZ = None
TEXT_CONTRACT = "text"
TBODY_ROWS_CONTRACT = "tbody_rows"
REQUIRED_KEY_FIELDS = (
"login_total",
"login_failed",
"session_total",
"risk_event_total",
)
REPORT_RUNTIME_REQUIRED_FIELDS = (
"output_path",
"output_exists",
"output_size_bytes",
"output_size_human",
"template_path",
"metadata_path",
"effective_org",
"switchable_orgs",
"queried_command_storage_ids",
"queried_command_storage_count",
"report_date",
"date_from",
"date_to",
"validation_summary",
)
SESSION_ERROR_REASON_LABEL_MAP = {
"Connect failed": "连接失败",
"connect_failed": "连接失败",
"Replay unsupported": "不支持回放",
"replay_unsupported": "不支持回放",
}
CHINESE_TEXT_RE = re.compile(r"[\u4e00-\u9fff]")
COMPONENT_PREFIX_RE = re.compile(r"^\[([^\[\]]+)\]")
LOGIN_REMAINING_TRIES_RE = re.compile(r"try\s+(\d+)\s+times?", re.IGNORECASE)
LOGIN_LOCKED_REASON_TEXT = "账号已锁定,请联系管理员解锁或 5 分钟后重试"
LOGIN_INVALID_CREDENTIALS_TEXT = "用户名或密码错误"
REPORT_ORG_SELECTION_REASON_CODE = "report_organization_not_accessible"
REPORT_DATE_ARGUMENT_REASON_CODE = "invalid_report_date_arguments"
def _local_now() -> datetime:
if SHANGHAI_TZ is not None:
return datetime.now(SHANGHAI_TZ)
return datetime.now().astimezone()
def load_report_metadata() -> dict[str, Any]:
payload = json.loads(REPORT_METADATA_PATH.read_text(encoding="utf-8"))
if not isinstance(payload, dict):
raise CLIError("Report metadata must be a JSON object.")
return payload
def load_report_template() -> str:
return REPORT_TEMPLATE_PATH.read_text(encoding="utf-8")
def _default_report_output_path(report_date: str) -> Path:
date_token = str(report_date or "").strip() or _local_now().date().isoformat()
return SKILL_DIR / "reports" / ("JumpServer-%s.html" % date_token)
def _format_output_size_human(size_bytes: int) -> str:
size = float(max(int(size_bytes or 0), 0))
if size < 1024:
return "%d B" % int(size)
for unit in ("KB", "MB", "GB", "TB", "PB"):
size /= 1024.0
if size < 1024.0 or unit == "PB":
return "%.1f %s" % (size, unit)
return "%.1f PB" % size
def _collect_report_artifact_metadata(output_path: Path) -> dict[str, Any]:
try:
output_exists = output_path.exists() and output_path.is_file()
except OSError:
output_exists = False
output_size_bytes = 0
if output_exists:
try:
output_size_bytes = int(output_path.stat().st_size or 0)
except OSError:
output_exists = False
output_size_bytes = 0
return {
"output_exists": output_exists,
"output_size_bytes": output_size_bytes,
"output_size_human": _format_output_size_human(output_size_bytes),
}
def extract_template_fields(template_html: str) -> list[str]:
return sorted(set(PLACEHOLDER_RE.findall(template_html)))
def _normalize_report_org_context(
org_id: str | None, org_name: str | None = None
) -> dict[str, Any]:
accessible_orgs = list_accessible_orgs()
requested_org_id = str(org_id or "").strip()
requested_org_name = str(org_name or "").strip()
if requested_org_id and requested_org_name:
raise CLIError(
"报告组织参数冲突。",
payload=build_cli_guidance_payload(
REPORT_DATE_ARGUMENT_REASON_CODE,
user_message="报告生成只能使用 `--org-id` 或 `--org-name` 其中一个。",
action_hint="请保留一个组织定位参数后重试。",
org_id=requested_org_id,
org_name=requested_org_name,
),
)
if requested_org_id:
matches = [
item
for item in accessible_orgs
if str(item.get("id") or "").strip() == requested_org_id
]
elif requested_org_name:
wanted = requested_org_name.lower()
matches = [
item
for item in accessible_orgs
if str(item.get("name") or "").strip().lower() == wanted
]
else:
matches = [
item
for item in accessible_orgs
if str(item.get("id") or "").strip() == GLOBAL_ORG_ID
]
if not matches:
raise CLIError(
"当前环境下无法访问目标报告组织。",
payload=build_cli_guidance_payload(
REPORT_ORG_SELECTION_REASON_CODE,
user_message="当前账号下找不到你指定的报告组织,请先确认可访问组织范围。",
action_hint="可以先执行 `python3 jumpserver-runtime-setup/scripts/jms_diagnose.py ping` 查看 `candidate_orgs`,再改用精确的 `--org-id` 或 `--org-name`。",
org_id=requested_org_id or None,
org_name=requested_org_name or None,
candidate_orgs=accessible_orgs,
),
)
if len(matches) > 1:
raise CLIError(
"给定的报告组织名称匹配到多个候选组织。",
payload=build_cli_guidance_payload(
REPORT_ORG_SELECTION_REASON_CODE,
user_message="当前 `--org-name` 命中了多个组织,请改用更精确的名称或直接使用 `--org-id`。",
action_hint="建议先从 `candidate_orgs` 中复制准确的 org_id。",
org_name=requested_org_name or None,
candidate_orgs=matches[:10],
),
)
selected = matches[0]
target_org_id = str(selected.get("id") or "").strip() or GLOBAL_ORG_ID
effective_org = dict(selected)
effective_org["source"] = (
"explicit"
if requested_org_id or requested_org_name
else "report_default_global"
)
switchable_orgs = [
item
for item in accessible_orgs
if str(item.get("id") or "").strip()
and str(item.get("id") or "").strip() != target_org_id
]
return {
"effective_org": effective_org,
"switchable_orgs": switchable_orgs,
"switchable_org_count": len(switchable_orgs),
"candidate_orgs": accessible_orgs,
"target_org_id": target_org_id,
}
@contextmanager
def _temporary_org_context(org_id: str):
previous = os.environ.get("JMS_ORG_ID")
os.environ["JMS_ORG_ID"] = org_id
try:
yield
finally:
if previous is None:
os.environ.pop("JMS_ORG_ID", None)
else:
os.environ["JMS_ORG_ID"] = previous
def _parse_date_expr(value: str, *, reference_date: date) -> date:
text = str(value or "").strip()
compact = text.replace(" ", "")
if not compact:
raise CLIError("Date expression is required.")
if compact == "昨天":
return reference_date - timedelta(days=1)
parsed_date = parse_date_value(compact)
if parsed_date is not None:
return parsed_date
match = DATE_COMPACT_RE.fullmatch(compact)
if match:
return date(
int(match.group("year")), int(match.group("month")), int(match.group("day"))
)
match = DATE_CN_RE.fullmatch(compact)
if match:
year = int(match.group("year") or reference_date.year)
return date(year, int(match.group("month")), int(match.group("day")))
raise CLIError("Unsupported date expression: %s" % value)
def _parse_datetime_expr(value: str, *, end_of_day: bool = False) -> datetime:
text = str(value or "").strip()
parsed = parse_datetime_value(text, naive_tz=SHANGHAI_TZ)
if parsed is not None:
if SHANGHAI_TZ is not None:
return parsed.astimezone(SHANGHAI_TZ)
return parsed.astimezone() if parsed.tzinfo is None else parsed.astimezone()
parsed_date = _parse_date_expr(text, reference_date=_local_now().date())
hour, minute, second = (23, 59, 59) if end_of_day else (0, 0, 0)
parsed = datetime(
parsed_date.year, parsed_date.month, parsed_date.day, hour, minute, second
)
return parsed.replace(tzinfo=SHANGHAI_TZ) if SHANGHAI_TZ else parsed.astimezone()
def _normalize_time_window(
*,
date_expr: str | None,
period_expr: str | None,
date_from_expr: str | None,
date_to_expr: str | None,
) -> dict[str, str]:
now = _local_now()
modes = sum(
[
bool(str(date_expr or "").strip()),
bool(str(period_expr or "").strip()),
bool(str(date_from_expr or "").strip() or str(date_to_expr or "").strip()),
]
)
if modes != 1:
raise CLIError(
"报告时间参数不完整或互相冲突。",
payload=build_cli_guidance_payload(
REPORT_DATE_ARGUMENT_REASON_CODE,
user_message="`daily-usage` 只能三选一:`--date`、`--period`、或 `--date-from + --date-to`。",
action_hint="请只保留一种时间写法后重试。",
suggested_commands=[
"python3 jumpserver-usage-reporting/scripts/jms_report.py daily-usage --date 20260310",
"python3 jumpserver-usage-reporting/scripts/jms_report.py daily-usage --period 上周",
"python3 jumpserver-usage-reporting/scripts/jms_report.py daily-usage --date-from '2026-03-10 00:00:00' --date-to '2026-03-24 23:59:59'",
],
),
)
if str(date_from_expr or "").strip() or str(date_to_expr or "").strip():
if not str(date_from_expr or "").strip() or not str(date_to_expr or "").strip():
raise CLIError(
"显式时间范围参数不完整。",
payload=build_cli_guidance_payload(
REPORT_DATE_ARGUMENT_REASON_CODE,
user_message="显式时间范围必须同时提供 `--date-from` 和 `--date-to`。",
action_hint="请把开始时间和结束时间成对传入。",
suggested_commands=[
"python3 jumpserver-usage-reporting/scripts/jms_report.py daily-usage --date-from '2026-03-10 00:00:00' --date-to '2026-03-24 23:59:59'",
],
),
)
date_from = _parse_datetime_expr(str(date_from_expr), end_of_day=False)
date_to = _parse_datetime_expr(str(date_to_expr), end_of_day=True)
elif str(date_expr or "").strip():
parsed_date = _parse_date_expr(str(date_expr), reference_date=now.date())
date_from = datetime(
parsed_date.year,
parsed_date.month,
parsed_date.day,
0,
0,
0,
tzinfo=now.tzinfo,
)
date_to = datetime(
parsed_date.year,
parsed_date.month,
parsed_date.day,
23,
59,
59,
tzinfo=now.tzinfo,
)
else:
period = str(period_expr or "").strip()
if period == "上周":
this_week_start = now.date() - timedelta(days=now.date().weekday())
period_start = this_week_start - timedelta(days=7)
period_end = period_start + timedelta(days=6)
elif period == "本月":
period_start = now.date().replace(day=1)
period_end = now.date()
else:
raise CLIError(
"暂不支持的周期表达:%s" % period,
payload=build_cli_guidance_payload(
REPORT_DATE_ARGUMENT_REASON_CODE,
user_message="当前 `--period` 只支持 `上周` 和 `本月`。",
action_hint="请改用支持的周期表达,或改用 `--date` / `--date-from` + `--date-to`。",
),
)
date_from = datetime(
period_start.year,
period_start.month,
period_start.day,
0,
0,
0,
tzinfo=now.tzinfo,
)
date_to = datetime(
period_end.year,
period_end.month,
period_end.day,
23,
59,
59,
tzinfo=now.tzinfo,
)
if date_to < date_from:
raise CLIError(
"报告时间范围非法。",
payload=build_cli_guidance_payload(
REPORT_DATE_ARGUMENT_REASON_CODE,
user_message="`date_to` 必须大于或等于 `date_from`。",
action_hint="请检查开始时间和结束时间是否写反。",
),
)
report_date = date_to.date().isoformat()
generated_at = now.strftime("%Y-%m-%d %H:%M:%S")
return {
"report_date": report_date,
"date_from": date_from.strftime("%Y-%m-%d %H:%M:%S"),
"date_to": date_to.strftime("%Y-%m-%d %H:%M:%S"),
"generated_at": generated_at,
"current_date": generated_at,
}
def _unwrap_single_result_layers(payload: Any) -> Any:
current = payload
while isinstance(current, dict) and "result" in current:
other_keys = [key for key in current if key not in {"ok", "result"}]
if other_keys:
break
current = current.get("result")
return current
def _extract_city(item: dict[str, Any]) -> str:
return _string_value(
_first_field(
item,
"city",
"city_display",
"location",
"location_display",
"geoip.city",
"addr_city",
"detail.city",
)
).strip()
def _extract_reason(item: dict[str, Any]) -> str:
return _string_value(
_first_field(
item,
"error_reason.label",
"error_reason.value",
"error_reason",
"reason",
"detail",
"message",
"error",
"type",
)
).strip()
def _extract_session_error_reason(item: dict[str, Any]) -> str:
return _string_value(
_first_field(item, "error_reason.label", "error_reason.value")
).strip()
def _display_session_error_reason(item: dict[str, Any]) -> str:
label = _string_value(_first_field(item, "error_reason.label")).strip()
value = _string_value(_first_field(item, "error_reason.value")).strip()
if label:
if CHINESE_TEXT_RE.search(label):
return label
return SESSION_ERROR_REASON_LABEL_MAP.get(label, label)
if value:
return SESSION_ERROR_REASON_LABEL_MAP.get(value, value)
return ""
def _extract_bracket_component(value: Any) -> str:
text = _string_value(value).strip()
if not text:
return ""
match = COMPONENT_PREFIX_RE.match(text)
if match:
component = str(match.group(1) or "").strip()
if component:
return component
return text
def _extract_component(item: dict[str, Any]) -> str:
for candidate in (
"terminal_display",
"terminal.name",
"terminal",
"component",
"component_display",
"terminal_name",
"terminal.type",
"terminal_type",
):
value = _first_field(item, candidate)
if value in {None, ""}:
continue
component = _extract_bracket_component(value)
if component:
return component
return ""
def _extract_login_failure_reason(item: dict[str, Any]) -> str:
return _string_value(
_first_field(
item,
"reason",
"detail",
"message",
"error",
"type.label",
"type.value",
"type",
)
).strip()
def _display_login_failure_reason(item: dict[str, Any]) -> str:
raw_reason = _extract_login_failure_reason(item)
if not raw_reason:
return ""
if CHINESE_TEXT_RE.search(raw_reason):
return raw_reason
lowered = raw_reason.lower()
if "account has been locked" in lowered:
return LOGIN_LOCKED_REASON_TEXT
if "username or password" in lowered and (
"incorrect" in lowered or "wrong" in lowered
):
match = LOGIN_REMAINING_TRIES_RE.search(raw_reason)
if match:
return "%s,还可再尝试 %s 次" % (
LOGIN_INVALID_CREDENTIALS_TEXT,
match.group(1),
)
return LOGIN_INVALID_CREDENTIALS_TEXT
return raw_reason
def _display_login_failure_status(_: dict[str, Any]) -> str:
return "失败"
def _extract_command_text(item: dict[str, Any]) -> str:
return _string_value(
_first_field(
item,
"input",
"command",
"command_text",
"cmd",
"content",
"output",
)
).strip()
def _looks_failed_session(item: dict[str, Any]) -> bool:
if _extract_session_error_reason(item):
return True
return not parse_bool(item.get("is_success"), default=True)
def _session_failure_status(item: dict[str, Any]) -> str:
if _looks_failed_session(item):
return "失败"
status = _extract_status(item)
return status or EMPTY_TEXT
def _format_datetime(value: Any) -> str:
if isinstance(value, datetime):
dt = value.astimezone(SHANGHAI_TZ) if SHANGHAI_TZ and value.tzinfo else value
return dt.strftime("%Y-%m-%d %H:%M:%S")
if value in {None, ""}:
return EMPTY_TEXT
text = str(value).strip()
try:
parsed = _extract_datetime({"date_from": text})
except Exception: # noqa: BLE001
parsed = None
if parsed is not None:
return _format_datetime(parsed)
return text
def _format_duration(value: Any) -> str:
if value in {None, ""}:
return EMPTY_TEXT
try:
total_seconds = max(int(float(value)), 0)
except (TypeError, ValueError):
return str(value)
hours, remainder = divmod(total_seconds, 3600)
minutes, seconds = divmod(remainder, 60)
parts = []
if hours:
parts.append("%s小时" % hours)
if minutes:
parts.append("%s分" % minutes)
if seconds or not parts:
parts.append("%s秒" % seconds)
return "".join(parts)
def _percent(value: int, total: int) -> str:
if total <= 0:
return "0%"
return "%.2f%%" % ((float(value) / float(total)) * 100.0)
def _top_summary(counter: Counter[str], *, limit: int = 3) -> str:
rows = []
for key, count in counter.most_common(limit):
label = str(key or "").strip() or "unknown"
rows.append("%s(%s)" % (label, count))
return " / ".join(rows) if rows else EMPTY_TEXT
def _top_records_summary(
rows: list[dict[str, Any]],
*,
keys: tuple[str, ...],
count_key: str = "count",
limit: int = 3,
) -> str:
final = []
for item in rows[:limit]:
name = ""
for key in keys:
name = str(item.get(key) or "").strip()
if name:
break
final.append("%s(%s)" % (name or "unknown", item.get(count_key) or 0))
return " / ".join(final) if final else EMPTY_TEXT
def _risk_level_label(
risk_event_total: int,
login_failed: int,
high_risk_command_total: int,
file_transfer_total: int,
) -> str:
if risk_event_total >= 10 or high_risk_command_total >= 5 or login_failed >= 10:
return "高风险"
if (
risk_event_total >= 3
or high_risk_command_total > 0
or login_failed >= 3
or file_transfer_total >= 20
):
return "中风险"
return "低风险"
def _empty_row(colspan: int, text: str = EMPTY_TEXT) -> str:
return '<tr class="table-empty-row"><td colspan="%s">%s</td></tr>' % (
colspan,
escape(text),
)
def _row(cells: list[Any]) -> str:
return "<tr>%s</tr>" % "".join(
"<td>%s</td>" % escape(str(cell or EMPTY_TEXT)) for cell in cells
)
def _render_login_rows(records: list[dict[str, Any]]) -> str:
if not records:
return _empty_row(4)
return "".join(
_row(
[
_extract_user(item),
_extract_city(item),
_extract_source_ip(item),
_extract_status(item) or ("失败" if _is_failed_login(item) else "成功"),
]
)
for item in records[:10]
)
def _render_login_failed_rows(
records: list[dict[str, Any]], *, common_ips: set[str]
) -> str:
if not records:
return _empty_row(6)
return "".join(
_row(
[
_extract_user(item),
_extract_city(item),
_extract_source_ip(item),
"是" if _extract_source_ip(item) in common_ips else "否",
_display_login_failure_reason(item),
_display_login_failure_status(item),
]
)
for item in records[:10]
)
def _render_distribution_rows(
counter: Counter[str], *, total: int, first_label: str, colspan: int = 3
) -> str:
if not counter:
return _empty_row(colspan)
rows = []
for key, count in counter.most_common(10):
rows.append(_row([key or first_label, count, _percent(count, total)]))
return "".join(rows)
def _render_asset_rows(counter: Counter[str]) -> str:
if not counter:
return _empty_row(2)
return "".join(
_row([asset or "unknown", count]) for asset, count in counter.most_common(10)
)
def _render_duration_rows(rows: list[dict[str, Any]]) -> str:
if not rows:
return _empty_row(3)
return "".join(
_row(
[
item.get("user"),
item.get("asset"),
_format_duration(item.get("duration_seconds")),
]
)
for item in rows[:10]
)
def _render_session_failed_rows(rows: list[dict[str, Any]]) -> str:
if not rows:
return _empty_row(5)
return "".join(
_row(
[
_extract_user(item),
_extract_asset(item),
_extract_protocol(item),
_display_session_error_reason(item),
_session_failure_status(item),
]
)
for item in rows[:10]
)
def _render_command_risk_rows(rows: list[dict[str, Any]]) -> str:
if not rows:
return _empty_row(7)
return "".join(
_row(
[
_extract_user(item),
_extract_asset(item),
_extract_account(item),
_extract_command_text(item),
_format_datetime(_extract_datetime(item)),
_format_datetime(
_first_field(item, "date_end", "date_finished", "date_to")
),
_string_value(
_first_field(
item, "risk_level_display", "risk_level.value", "risk_level"
)
),
]
)
for item in rows[:10]
)
def _normalize_direction(value: str) -> str:
text = str(value or "").strip().lower()
if any(token in text for token in ("upload", "up", "上传")):
return "upload"
if any(token in text for token in ("download", "down", "下载")):
return "download"
return text or "unknown"
def _get_path_value(payload: dict[str, Any], path: str) -> Any:
current: Any = payload
for part in path.split("."):
if isinstance(current, dict):
current = current.get(part)
else:
return None
return current
def _evaluate_output_expression(payload: dict[str, Any], expression: str) -> Any:
match = re.fullmatch(r"\s*([a-zA-Z0-9_.]+)\s*-\s*([a-zA-Z0-9_.]+)\s*", expression)
if not match:
return _get_path_value(payload, expression)
left = _get_path_value(payload, match.group(1))
right = _get_path_value(payload, match.group(2))
try:
return int(left or 0) - int(right or 0)
except (TypeError, ValueError):
return None
def _normalize_license_source() -> dict[str, Any]:
payload = _unwrap_single_result_layers(license_detail_query({}))
records = payload.get("records") if isinstance(payload, dict) else None
record = records[0] if isinstance(records, list) and records else {}
return dict(record or {})
def _normalize_login_source(filters: dict[str, Any]) -> dict[str, Any]:
records = list(_login_records(filters))
records.sort(
key=lambda item: _extract_datetime(item)
or datetime.min.replace(tzinfo=_local_now().tzinfo),
reverse=True,
)
failed_records = [item for item in records if _is_failed_login(item)]
success_records = [item for item in records if not _is_failed_login(item)]
city_counter = Counter(
city for city in (_extract_city(item) for item in records) if city
)
ip_counter = Counter(
ip for ip in (_extract_source_ip(item) for item in records) if ip
)
common_ips = {ip for ip, count in ip_counter.items() if count > 1}
if not common_ips and ip_counter:
common_ips = {ip for ip, _ in ip_counter.most_common(3)}
return {
"login_total": len(records),
"login_success": len(success_records),
"login_failed": len(failed_records),
"unique_login_city_count": len(city_counter),
"top_login_ip_summary": _top_summary(ip_counter),
"rows_html": _render_login_rows(records),
"login_failed_rows": _render_login_failed_rows(
failed_records, common_ips=common_ips
),
"records": records,
"failed_records": failed_records,
}
def _normalize_session_source(filters: dict[str, Any]) -> dict[str, Any]:
records = list(_fetch_session_records(filters))
records.sort(
key=lambda item: _extract_datetime(item)
or datetime.min.replace(tzinfo=_local_now().tzinfo),
reverse=True,
)
durations = [
value
for value in (_extract_duration(item) for item in records)
if value is not None
]
total_duration = sum(durations) if durations else 0.0
protocol_counter = Counter(_extract_protocol(item) or "unknown" for item in records)
component_counter = Counter(
_extract_component(item) or "unknown" for item in records
)
user_counter = Counter(_extract_user(item) or "unknown" for item in records)
asset_counter = Counter(_extract_asset(item) or "unknown" for item in records)
duration_rows = []
for item in records:
duration = _extract_duration(item)
if duration is None:
continue
duration_rows.append(
{
"user": _extract_user(item),
"asset": _extract_asset(item),
"duration_seconds": duration,
"timestamp": _extract_datetime(item),
}
)
duration_rows.sort(key=lambda item: item.get("duration_seconds") or 0, reverse=True)
failed_records = [item for item in records if _looks_failed_session(item)]
return {
"session_total": len(records),
"session_total_duration": _format_duration(total_duration),
"avg_session_duration": _format_duration(
(total_duration / len(durations)) if durations else None
),
"longest_session": (
"%s / %s / %s"
% (
duration_rows[0].get("user") or "unknown",
duration_rows[0].get("asset") or "unknown",
_format_duration(duration_rows[0].get("duration_seconds")),
)
if duration_rows
else EMPTY_TEXT
),
"protocol_distribution_rows": _render_distribution_rows(
protocol_counter, total=len(records), first_label="协议"
),
"component_distribution_rows": _render_distribution_rows(
component_counter, total=len(records), first_label="组件"
),
"session_user_top10_rows": _render_distribution_rows(
user_counter, total=len(records), first_label="用户"
),
"session_asset_top10_rows": _render_asset_rows(asset_counter),
"session_duration_top10_rows": _render_duration_rows(duration_rows),
"session_failed_rows": _render_session_failed_rows(failed_records),
"records": records,
"failed_records": failed_records,
}
def _build_command_filters(
filters: dict[str, Any], command_storage_id: str | None
) -> dict[str, Any]:
payload = {
"date_from": filters["date_from"],
"date_to": filters["date_to"],
"limit": 50,
}
if command_storage_id:
payload["command_storage_id"] = str(command_storage_id)
else:
payload["command_storage_scope"] = "all"
return payload
def _normalize_command_source(
filters: dict[str, Any], command_storage_id: str | None
) -> dict[str, Any]:
command_filters = _build_command_filters(filters, command_storage_id)
records = list(_fetch_command_records(command_filters))
risk_counter = Counter(
str(
_string_value(
_first_field(
item, "risk_level_display", "risk_level.value", "risk_level"
)
)
or "unknown"
)
for item in records
)
user_counter = Counter(_extract_user(item) or "unknown" for item in records)
asset_counter = Counter(_extract_asset(item) or "unknown" for item in records)
storage_context = resolve_command_storage_context(command_filters)
return {
"command_total": len(records),
"top_command_users": _top_summary(user_counter),
"top_command_assets": _top_summary(asset_counter),
"risk_levels": [
{"name": key, "count": value} for key, value in risk_counter.most_common(10)
],
"records": records,
**storage_context,
}
def _normalize_high_risk_command_source(
command_source: dict[str, Any],
) -> dict[str, Any]:
records = [
item
for item in command_source.get("records", [])
if int(_first_field(item, "risk_level.value", "risk_level") or 0) >= 4
]
return {
"high_risk_command_total": len(records),
"rows_html": _render_command_risk_rows(records),
"records": records,
}
def _normalize_file_transfer_source(filters: dict[str, Any]) -> dict[str, Any]:
records = list(_fetch_file_transfer_records(filters))
direction_counter = Counter(
_normalize_direction(_extract_direction(item)) for item in records
)
user_counter = Counter(_extract_user(item) or "unknown" for item in records)
asset_counter = Counter(_extract_asset(item) or "unknown" for item in records)