zt-zlp-cli 0.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: zt-zlp-cli
3
+ Version: 0.0.1
4
+ Summary: ZLP CLI
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: playwright>=1.40.0
8
+ Requires-Dist: requests>=2.31.0
9
+ Requires-Dist: click>=8.1.0
10
+ Requires-Dist: pyyaml>=6.0
11
+
12
+ # zt-zlp-cli
13
+
14
+ ZLP 日志管理平台 命令行工具,用于登录并查询实例、库、表结构与 SQL 结果。
15
+
16
+ ## 环境要求
17
+
18
+ - Python `>=3.10`
19
+ - 可用浏览器(首次登录会自动打开)
20
+
21
+ ## 安装
22
+
23
+ ### 开发安装(源码)
24
+
25
+ ```bash
26
+ pip install -e .
27
+ ```
28
+
29
+ ### 打包发布
30
+
31
+ ```bash
32
+ python -m pip install --upgrade build twine
33
+ python -m build
34
+ twine upload dist/*
35
+ ```
36
+
37
+ ## 快速开始
38
+
39
+ ### 1) 登录并缓存 Cookie
40
+
41
+ 首次运行会打开浏览器,请完成登录。成功后会缓存 Cookie 到本地。
42
+
43
+ ```bash
44
+ zt-zlp-cli login
45
+ ```
46
+
47
+ ### 2) 获取系统列表
48
+
49
+ ```bash
50
+ zt-zlp-cli discover systems
51
+ ```
52
+
53
+
54
+ ### 2) 获取服务列表
55
+
56
+ ```bash
57
+ zt-zlp-cli discover services --system LMS --log-type json
58
+ ```
59
+
60
+ ### 2.1) 日志搜索
61
+
62
+ ```bash
63
+ zt-zlp-cli discover logs \
64
+ --system LMS \
65
+ --service fbu-lms-labelservice-pro-json \
66
+ --log-type json \
67
+ --custom-sql "select topic,ClientIp,PrintMethod from \$table limit 10" \
68
+ --query-statement "SiteName = 'CN'" \
69
+ --start-time "2026-04-12 00:00:00" \
70
+ --end-time "2026-04-14 23:59:59"
71
+ ```
72
+
73
+ ## 全局参数
74
+ - `-o, --output`:输出格式,支持:
75
+ - `json`(默认)
76
+ - `human`(表格)
77
+
78
+ 示例:
79
+
80
+ ```bash
81
+ zt-zlp-cli -o human sql instances
82
+ ```
83
+
84
+ ## 配置说明
85
+
86
+ 默认配置目录:`~/.zt-zlp-cli`
87
+ - Cookie 缓存:`~/.zt-zlp-cli/cookies.json`
88
+ - 配置文件:`~/.zt-zlp-cli/config.yaml`
89
+
90
+ ## 环境变量(可选)
91
+
92
+ 支持通过环境变量自动填充登录页账号密码(如 SSO 页面字段可用):
93
+
94
+ - `ZT_SSO_USERNAME`
95
+ - `ZT_SSO_PASSWORD`
96
+
97
+ 未设置时可在浏览器中手动完成登录。
@@ -0,0 +1,86 @@
1
+ # zt-zlp-cli
2
+
3
+ ZLP 日志管理平台 命令行工具,用于登录并查询实例、库、表结构与 SQL 结果。
4
+
5
+ ## 环境要求
6
+
7
+ - Python `>=3.10`
8
+ - 可用浏览器(首次登录会自动打开)
9
+
10
+ ## 安装
11
+
12
+ ### 开发安装(源码)
13
+
14
+ ```bash
15
+ pip install -e .
16
+ ```
17
+
18
+ ### 打包发布
19
+
20
+ ```bash
21
+ python -m pip install --upgrade build twine
22
+ python -m build
23
+ twine upload dist/*
24
+ ```
25
+
26
+ ## 快速开始
27
+
28
+ ### 1) 登录并缓存 Cookie
29
+
30
+ 首次运行会打开浏览器,请完成登录。成功后会缓存 Cookie 到本地。
31
+
32
+ ```bash
33
+ zt-zlp-cli login
34
+ ```
35
+
36
+ ### 2) 获取系统列表
37
+
38
+ ```bash
39
+ zt-zlp-cli discover systems
40
+ ```
41
+
42
+
43
+ ### 2) 获取服务列表
44
+
45
+ ```bash
46
+ zt-zlp-cli discover services --system LMS --log-type json
47
+ ```
48
+
49
+ ### 2.1) 日志搜索
50
+
51
+ ```bash
52
+ zt-zlp-cli discover logs \
53
+ --system LMS \
54
+ --service fbu-lms-labelservice-pro-json \
55
+ --log-type json \
56
+ --custom-sql "select topic,ClientIp,PrintMethod from \$table limit 10" \
57
+ --query-statement "SiteName = 'CN'" \
58
+ --start-time "2026-04-12 00:00:00" \
59
+ --end-time "2026-04-14 23:59:59"
60
+ ```
61
+
62
+ ## 全局参数
63
+ - `-o, --output`:输出格式,支持:
64
+ - `json`(默认)
65
+ - `human`(表格)
66
+
67
+ 示例:
68
+
69
+ ```bash
70
+ zt-zlp-cli -o human sql instances
71
+ ```
72
+
73
+ ## 配置说明
74
+
75
+ 默认配置目录:`~/.zt-zlp-cli`
76
+ - Cookie 缓存:`~/.zt-zlp-cli/cookies.json`
77
+ - 配置文件:`~/.zt-zlp-cli/config.yaml`
78
+
79
+ ## 环境变量(可选)
80
+
81
+ 支持通过环境变量自动填充登录页账号密码(如 SSO 页面字段可用):
82
+
83
+ - `ZT_SSO_USERNAME`
84
+ - `ZT_SSO_PASSWORD`
85
+
86
+ 未设置时可在浏览器中手动完成登录。
@@ -0,0 +1,22 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "zt-zlp-cli"
7
+ version = "0.0.1"
8
+ description = "ZLP CLI"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ dependencies = [
12
+ "playwright>=1.40.0",
13
+ "requests>=2.31.0",
14
+ "click>=8.1.0",
15
+ "pyyaml>=6.0",
16
+ ]
17
+
18
+ [project.scripts]
19
+ zt-zlp-cli = "zt_zlp_cli.cli:main"
20
+
21
+ [tool.pytest.ini_options]
22
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
File without changes
@@ -0,0 +1,125 @@
1
+ """ZLP Admin HTTP API 请求封装(与 docs/curl.md 中接口一致)"""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ from typing import Any
6
+ from urllib.parse import quote, urlparse
7
+ import requests
8
+ from .auth import get_auth_cookies, get_auth_headers
9
+
10
+
11
+ class ZlpApi:
12
+ """ZLP 日志发现相关 REST API 客户端"""
13
+
14
+ _DEFAULT_BASE = "https://zlp-admin.ztn.cn"
15
+ _DEFAULT_OPENAPI_BASE = "https://zlp-openapi.ztn.cn"
16
+
17
+ def __init__(
18
+ self,
19
+ *,
20
+ base_url: str | None = None
21
+ ):
22
+ self.base_url = (
23
+ base_url or os.environ.get("ZLP_BASE_URL") or self._DEFAULT_BASE
24
+ ).rstrip("/")
25
+
26
+
27
+ @staticmethod
28
+ def _normalize_bearer(token: str | None) -> str | None:
29
+ if not token:
30
+ return None
31
+ t = token.strip()
32
+ if t.lower().startswith("bearer "):
33
+ return t[7:].strip()
34
+ return t
35
+
36
+ def _request(self, method: str, path: str, *, json_body: dict[str, Any] | None = None) -> Any:
37
+ path = path if path.startswith("/") else f"/{path}"
38
+ url = f"{self.base_url}{path}"
39
+ cookies = get_auth_cookies()
40
+ headers = get_auth_headers(cookies)
41
+ body: dict[str, Any] = json_body if json_body is not None else {}
42
+ response = requests.request(
43
+ method=method,
44
+ url=url,
45
+ headers=headers,
46
+ cookies=cookies,
47
+ json=body,
48
+ timeout=120,
49
+ )
50
+ if response.status_code >= 400:
51
+ raise RuntimeError(f"API 错误: {response.status_code} {response.text}")
52
+ try:
53
+ return response.json()
54
+ except ValueError:
55
+ return response.text
56
+
57
+ def _request_openapi(self, method: str, path: str, *, json_body: dict[str, Any] | None = None) -> Any:
58
+ path = path if path.startswith("/") else f"/{path}"
59
+ openapi_base = os.environ.get("ZLP_OPENAPI_BASE_URL", self._DEFAULT_OPENAPI_BASE).rstrip("/")
60
+ url = f"{openapi_base}{path}"
61
+ cookies = get_auth_cookies()
62
+ headers = get_auth_headers(cookies)
63
+ token = self._normalize_bearer(cookies.get("Authorization", ""))
64
+ if token:
65
+ headers["Authorization"] = f"Bearer {token}"
66
+ body: dict[str, Any] = json_body if json_body is not None else {}
67
+ response = requests.request(
68
+ method=method,
69
+ url=url,
70
+ headers=headers,
71
+ cookies=cookies,
72
+ json=body,
73
+ timeout=120,
74
+ )
75
+ if response.status_code >= 400:
76
+ raise RuntimeError(f"API 错误: {response.status_code} {response.text}")
77
+ try:
78
+ return response.json()
79
+ except ValueError:
80
+ return response.text
81
+
82
+ def system_list(self) -> Any:
83
+ """POST /zlpApi/query/queryExistSystemList,请求体 {}"""
84
+ return self._request("POST", "/zlpApi/query/queryExistSystemList", json_body={})
85
+
86
+ def service_list(
87
+ self,
88
+ log_type_id: int,
89
+ system_name: str
90
+ ) -> Any:
91
+ """POST /zlpApi/query/queryServiceNameList"""
92
+ payload = {
93
+ "logTypeId": log_type_id,
94
+ "systemName": system_name,
95
+ "startDate":"2020-04-10 06:41:47",
96
+ "endDate":"2026-04-10 06:56:47",
97
+ "queryStatement":""
98
+ }
99
+ return self._request("POST", "/zlpApi/query/queryServiceNameList", json_body=payload)
100
+
101
+
102
+ def search_logs(
103
+ self,
104
+ *,
105
+ custom_sql: str,
106
+ log_type_id: int,
107
+ system_name: str,
108
+ service_name: str,
109
+ start_date: str,
110
+ end_date: str,
111
+ query_statement: str = "",
112
+ chart_type: str = "TABLE",
113
+ ) -> Any:
114
+ """POST /zlpApi/dataAnalysis/searchAggregateBySql"""
115
+ payload = {
116
+ "customSql": custom_sql,
117
+ "logTypeId": log_type_id,
118
+ "systemName": system_name,
119
+ "serviceName": service_name,
120
+ "startDate": start_date,
121
+ "endDate": end_date,
122
+ "queryStatement": query_statement,
123
+ "chartType": chart_type,
124
+ }
125
+ return self._request("POST", "/zlpApi/dataAnalysis/searchAggregateBySql", json_body=payload)
@@ -0,0 +1,166 @@
1
+ """认证模块 - 通过 Playwright 获取浏览器 cookie"""
2
+ import json
3
+ import os
4
+
5
+ from playwright.sync_api import sync_playwright
6
+
7
+ from .config import config
8
+
9
+
10
+ # DevOps 域名
11
+ ZT_ADMIN_DOMAIN = "zlp-admin.ztn.cn"
12
+
13
+ # Archery 页面(会自动跳转 SSO)
14
+ ZT_ADMIN_LOGIN_URL = "https://zlp-admin.ztn.cn/discover"
15
+
16
+ def save_cookies(cookies: dict):
17
+ """保存 cookie 到缓存文件"""
18
+ config.CONFIG_DIR.mkdir(parents=True, exist_ok=True)
19
+ with open(config.COOKIE_FILE, "w") as f:
20
+ json.dump(cookies, f)
21
+
22
+ def load_cookies() -> dict:
23
+ """从缓存文件加载 cookie"""
24
+ if config.COOKIE_FILE.exists():
25
+ with open(config.COOKIE_FILE) as f:
26
+ return json.load(f)
27
+ return {}
28
+
29
+ def get_auth_headers(cookies: dict) -> dict:
30
+ """从 cookie 构建认证请求头"""
31
+ return {
32
+ "Accept": "application/json, text/javascript, */*; q=0.01",
33
+ "Accept-Language": "zh-CN,zh;q=0.9",
34
+ "Origin": "https://zlp-admin.ztn.cn/discover",
35
+ "Referer": "https://zlp-admin.ztn.cn/discover",
36
+ "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/144.0.0.0 Safari/537.36",
37
+ "Authorization": cookies.get("Authorization", ""),
38
+ "X-Requested-With": "XMLHttpRequest"
39
+ }
40
+
41
+ def get_auth_cookies() -> dict:
42
+ """获取认证 cookie,优先使用缓存,失效则重新获取"""
43
+ cookies = load_cookies()
44
+
45
+ # 检查必要的 cookie 是否存在
46
+ required = ["ztCookie","Authorization","JSESSIONID"]
47
+ if all(cookies.get(k) for k in required):
48
+ return cookies
49
+
50
+ # 缓存失效,重新获取
51
+ cookies = get_cookies_from_browser()
52
+ save_cookies(cookies)
53
+
54
+ print(f"已获取新的 cookie: {cookies}")
55
+ return cookies
56
+
57
+ def open_login_page(page) -> bool:
58
+ """自动登录 - 尝试读取环境变量自动填写账号密码"""
59
+ username = os.environ.get("ZT_SSO_USERNAME")
60
+ password = os.environ.get("ZT_SSO_PASSWORD")
61
+
62
+ if not username or not password:
63
+ return False
64
+
65
+ print(f"检测到环境变量,自动登录中...")
66
+
67
+ # 等待页面加载
68
+ page.wait_for_selector("#username")
69
+
70
+ try:
71
+ # 填写用户名
72
+ page.fill("#username", username)
73
+ print(f"已填写用户名")
74
+
75
+ # 填写密码 - 使用 #password2
76
+ page.fill("#password2", password)
77
+ print(f"已填写密码")
78
+
79
+ # 点击登录按钮
80
+ page.click(".login_in")
81
+ print("已点击登录按钮")
82
+
83
+ return True
84
+
85
+ except Exception as e:
86
+ print(f"自动登录失败: {e}")
87
+
88
+ return False
89
+
90
+ def get_cookies_from_browser(headless: bool = True) -> dict:
91
+ """通过 Playwright 从浏览器获取 cookie"""
92
+ if headless:
93
+ print("正在启动浏览器(无头模式),请登录...")
94
+ else:
95
+ print("正在打开浏览器,请登录...")
96
+
97
+ with sync_playwright() as p:
98
+ browser = p.chromium.launch(headless=headless)
99
+ context = browser.new_context()
100
+ page = context.new_page()
101
+
102
+ # 导航到 SSO 登录页
103
+ page.goto(ZT_ADMIN_LOGIN_URL)
104
+
105
+ # 尝试自动登录
106
+ if not open_login_page(page):
107
+ if headless:
108
+ raise RuntimeError(
109
+ "无头模式下无法完成交互式登录。请设置环境变量 ZT_SSO_USERNAME 与 ZT_SSO_PASSWORD,"
110
+ "或执行 zt-zlp-cli login --headed 使用有界面浏览器登录。"
111
+ )
112
+ print("自动登陆失败. 请在浏览器中完成登录,登录成功后会自动继续...")
113
+
114
+ print("登陆中. 检测关键 cookie 出现")
115
+ page.wait_for_function(
116
+ f"""() => {{
117
+ const cookies = document.cookie;
118
+ return cookies.includes('Authorization');
119
+ }}""",
120
+ timeout=300000 # 5分钟超时
121
+ )
122
+
123
+ page.wait_for_function(
124
+ f"""() => {{
125
+ const t = localStorage.getItem('Token');
126
+ return t != null && String(t).trim().length > 0;
127
+ }}""",
128
+ timeout=300_000,
129
+ )
130
+
131
+ print("登录成功")
132
+
133
+ token = page.evaluate(
134
+ f"""() => localStorage.getItem('Token') || ''"""
135
+ )
136
+
137
+ print("登陆成功. 已获取关键 cookie")
138
+
139
+ # 获取所有 cookie
140
+ cookies = context.cookies()
141
+
142
+ # 提取需要的 cookie
143
+ cookie_dict = {}
144
+ for cookie in cookies:
145
+ if cookie["domain"] == ZT_ADMIN_DOMAIN or ZT_ADMIN_DOMAIN in cookie["domain"]:
146
+ cookie_dict[cookie["name"]] = cookie["value"]
147
+
148
+ cookie_dict["Authorization"] = token
149
+
150
+ browser.close()
151
+
152
+ return cookie_dict
153
+
154
+ def login(headless: bool = True) -> dict:
155
+ """手动登录 - 强制打开浏览器重新获取 cookie"""
156
+ if headless:
157
+ print("正在启动浏览器(无头模式),请重新登录...")
158
+ else:
159
+ print("正在打开浏览器,请重新登录...")
160
+ cookies = get_cookies_from_browser(headless=headless)
161
+ save_cookies(cookies)
162
+ print("登录成功,cookie 已缓存!")
163
+ return cookies
164
+
165
+ if __name__ == "__main__":
166
+ print(login())
@@ -0,0 +1,240 @@
1
+ """CLI 入口"""
2
+ import json
3
+ import shutil
4
+
5
+ import click
6
+
7
+ from .api import ZlpApi
8
+ from .auth import login
9
+
10
+ LOG_TYPE_TO_ID = {
11
+ "app": 1,
12
+ "json": 16,
13
+ }
14
+
15
+
16
+ def _normalize_cell(value):
17
+ if value is None:
18
+ return "-"
19
+ return str(value)
20
+
21
+
22
+ def _truncate_text(text, width):
23
+ if width <= 0:
24
+ return ""
25
+ if len(text) <= width:
26
+ return text
27
+ if width <= 1:
28
+ return text[:width]
29
+ return text[: width - 1] + "…"
30
+
31
+
32
+ def render_table(headers, rows, max_width=120, no_truncate_headers=None):
33
+ if not rows:
34
+ click.echo("暂无数据")
35
+ return
36
+
37
+ terminal_width = shutil.get_terminal_size((max_width, 20)).columns
38
+ table_max_width = min(max_width, terminal_width)
39
+
40
+ no_truncate_headers = set(no_truncate_headers or [])
41
+
42
+ normalized_rows = []
43
+ for row in rows:
44
+ normalized = [_normalize_cell(cell) for cell in row[: len(headers)]]
45
+ if len(normalized) < len(headers):
46
+ normalized.extend(["-"] * (len(headers) - len(normalized)))
47
+ normalized_rows.append(normalized)
48
+
49
+ widths = [len(h) for h in headers]
50
+ for row in normalized_rows:
51
+ for idx, cell in enumerate(row):
52
+ widths[idx] = max(widths[idx], len(cell))
53
+
54
+ overhead = 3 * len(headers) + 1
55
+ available = max(20, table_max_width - overhead)
56
+ min_col_width = 10
57
+ widths = [max(min_col_width, w) for w in widths]
58
+
59
+ total = sum(widths)
60
+ if total > available:
61
+ fixed_idx = {i for i, h in enumerate(headers) if h in no_truncate_headers}
62
+ shrinkable_idx = [i for i in range(len(headers)) if i not in fixed_idx]
63
+
64
+ if shrinkable_idx:
65
+ while sum(widths) > available:
66
+ idx = max(shrinkable_idx, key=lambda i: widths[i])
67
+ if widths[idx] > min_col_width:
68
+ widths[idx] -= 1
69
+ else:
70
+ if all(widths[i] <= min_col_width for i in shrinkable_idx):
71
+ break
72
+
73
+ def format_row(cells):
74
+ parts = []
75
+ for i, cell in enumerate(cells):
76
+ text = cell if headers[i] in no_truncate_headers else _truncate_text(cell, widths[i])
77
+ parts.append(f" {text.ljust(widths[i])} ")
78
+ return "|" + "|".join(parts) + "|"
79
+
80
+ border = "+" + "+".join("-" * (w + 2) for w in widths) + "+"
81
+ click.echo(border)
82
+ click.echo(format_row(headers))
83
+ click.echo(border)
84
+ for row in normalized_rows:
85
+ click.echo(format_row(row))
86
+ click.echo(border)
87
+
88
+
89
+ @click.group()
90
+ @click.option(
91
+ "--output",
92
+ "-o",
93
+ "output_format",
94
+ type=click.Choice(["human", "json"], case_sensitive=False),
95
+ default="json",
96
+ show_default=True,
97
+ help="输出格式: human(表格) / json",
98
+ )
99
+ @click.pass_context
100
+ def cli(ctx, output_format):
101
+ """ZLP 日志平台命令行工具"""
102
+ ctx.ensure_object(dict)
103
+ ctx.obj["output_format"] = output_format.lower()
104
+
105
+
106
+ @cli.command("login")
107
+ @click.option(
108
+ "--headed",
109
+ is_flag=True,
110
+ help="显示浏览器窗口,用于无环境变量时的手动登录",
111
+ )
112
+ def cmd_login(headed):
113
+ """登录 - 打开浏览器重新获取 cookie(默认无头;需手动登录时请传 --headed)"""
114
+ login(headless=not headed)
115
+
116
+
117
+ @cli.group()
118
+ def discover():
119
+ """日志发现相关 HTTP 接口(参见 docs/curl.md)"""
120
+ pass
121
+
122
+
123
+ def _extract_rows(result):
124
+ if isinstance(result, list):
125
+ return result
126
+ if isinstance(result, dict):
127
+ for key in ("data", "rows", "result", "results"):
128
+ value = result.get(key)
129
+ if isinstance(value, list):
130
+ return value
131
+ return []
132
+
133
+
134
+ def _print_result(ctx, result, preferred_headers=None):
135
+ output_format = ctx.obj["output_format"]
136
+ if output_format == "json":
137
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
138
+ return
139
+
140
+ rows = _extract_rows(result)
141
+ if not rows:
142
+ click.echo(json.dumps(result, ensure_ascii=False, indent=2))
143
+ return
144
+
145
+ if isinstance(rows[0], dict):
146
+ headers = preferred_headers or list(rows[0].keys())
147
+ table_rows = [[item.get(h) for h in headers] for item in rows]
148
+ render_table(headers, table_rows, no_truncate_headers=headers[:1])
149
+ return
150
+
151
+ if isinstance(rows[0], list):
152
+ headers = preferred_headers or [f"col_{idx + 1}" for idx in range(len(rows[0]))]
153
+ render_table(headers, rows)
154
+ return
155
+
156
+ render_table(["value"], [[row] for row in rows])
157
+
158
+
159
+ def _map_log_type_to_id(log_type: str) -> int:
160
+ """将 CLI 传入的 log_type 映射为 API 所需的 log_type_id。"""
161
+ return LOG_TYPE_TO_ID[log_type]
162
+
163
+
164
+ @discover.command("systems")
165
+ @click.pass_context
166
+ def discover_systems(ctx):
167
+ """查询已有系统列表(queryExistSystemList)"""
168
+ api = ZlpApi()
169
+ result = api.system_list()
170
+ rows = []
171
+ for item in result.get("data").get("systemInfoVoList"):
172
+ rows.append(item.get("systemAbbreviation"))
173
+
174
+ _print_result(ctx, rows)
175
+
176
+ @discover.command("services")
177
+ @click.option(
178
+ "--log-type",
179
+ type=click.Choice(["app", "json"], case_sensitive=False),
180
+ required=True,
181
+ help="日志类型,如 app / json",
182
+ )
183
+ @click.option("--system", "system_name", required=True, help="系统名,如 LMS / ELD")
184
+ @click.pass_context
185
+ def discover_services(ctx, log_type, system_name):
186
+ """查询服务名列表(queryServiceNameList)"""
187
+ api = ZlpApi()
188
+ result = api.service_list(
189
+ log_type_id=_map_log_type_to_id(log_type.lower()),
190
+ system_name=system_name
191
+ )
192
+ _print_result(ctx, result.get("data").get("serviceList"))
193
+
194
+ @discover.command("logs")
195
+ @click.option("--system", "system_name", required=True, help="系统名,如 LMS")
196
+ @click.option("--service", "service_name", required=True, help="服务名,如 fbu-lms-labelservice-pro-json")
197
+ @click.option(
198
+ "--log-type",
199
+ type=click.Choice(["app", "json"], case_sensitive=False),
200
+ required=True,
201
+ help="日志类型,如 app / json",
202
+ )
203
+ @click.option("--custom-sql", required=True, help="聚合 SQL,如 select topic,ClientIp from $table limit 10")
204
+ @click.option("--query-statement", default="", show_default=True, help="过滤条件,如 SiteName = 'CN'")
205
+ @click.option("--chart-type", default="TABLE", show_default=True, help="图表类型,默认 TABLE")
206
+ @click.option("--start-time", required=True, help="开始时间,格式:YYYY-MM-DD HH:MM:SS")
207
+ @click.option("--end-time", required=True, help="结束时间,格式:YYYY-MM-DD HH:MM:SS")
208
+ @click.pass_context
209
+ def discover_logs(
210
+ ctx,
211
+ system_name,
212
+ service_name,
213
+ log_type,
214
+ custom_sql,
215
+ query_statement,
216
+ chart_type,
217
+ start_time,
218
+ end_time,
219
+ ):
220
+ """按 SQL 搜索日志(searchAggregateBySql)"""
221
+ api = ZlpApi()
222
+ result = api.search_logs(
223
+ system_name=system_name,
224
+ service_name=service_name,
225
+ log_type_id=_map_log_type_to_id(log_type.lower()),
226
+ custom_sql=custom_sql,
227
+ query_statement=query_statement,
228
+ chart_type=chart_type,
229
+ start_date=start_time,
230
+ end_date=end_time,
231
+ )
232
+ _print_result(ctx, result)
233
+
234
+
235
+ def main():
236
+ cli()
237
+
238
+
239
+ if __name__ == "__main__":
240
+ main()
@@ -0,0 +1,33 @@
1
+ """配置管理模块"""
2
+ from pathlib import Path
3
+
4
+ import yaml
5
+
6
+
7
+ class Config:
8
+ """配置类"""
9
+
10
+ CONFIG_DIR = Path.home() / ".zt-zlp-cli"
11
+ COOKIE_FILE = CONFIG_DIR / "cookies.json"
12
+ CONFIG_FILE = CONFIG_DIR / "config.yaml"
13
+
14
+ # API 配置
15
+ BASE_URL = "https://archery.ztn.cn"
16
+
17
+ def __init__(self):
18
+ self._config = self._load_config()
19
+
20
+ def _load_config(self) -> dict:
21
+ """加载配置文件"""
22
+ if self.CONFIG_FILE.exists():
23
+ with open(self.CONFIG_FILE) as f:
24
+ return yaml.safe_load(f) or {}
25
+ return {}
26
+
27
+
28
+ @property
29
+ def browser_channel(self) -> str:
30
+ return self._config.get("browser_channel", "chromium")
31
+
32
+
33
+ config = Config()
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: zt-zlp-cli
3
+ Version: 0.0.1
4
+ Summary: ZLP CLI
5
+ Requires-Python: >=3.10
6
+ Description-Content-Type: text/markdown
7
+ Requires-Dist: playwright>=1.40.0
8
+ Requires-Dist: requests>=2.31.0
9
+ Requires-Dist: click>=8.1.0
10
+ Requires-Dist: pyyaml>=6.0
11
+
12
+ # zt-zlp-cli
13
+
14
+ ZLP 日志管理平台 命令行工具,用于登录并查询实例、库、表结构与 SQL 结果。
15
+
16
+ ## 环境要求
17
+
18
+ - Python `>=3.10`
19
+ - 可用浏览器(首次登录会自动打开)
20
+
21
+ ## 安装
22
+
23
+ ### 开发安装(源码)
24
+
25
+ ```bash
26
+ pip install -e .
27
+ ```
28
+
29
+ ### 打包发布
30
+
31
+ ```bash
32
+ python -m pip install --upgrade build twine
33
+ python -m build
34
+ twine upload dist/*
35
+ ```
36
+
37
+ ## 快速开始
38
+
39
+ ### 1) 登录并缓存 Cookie
40
+
41
+ 首次运行会打开浏览器,请完成登录。成功后会缓存 Cookie 到本地。
42
+
43
+ ```bash
44
+ zt-zlp-cli login
45
+ ```
46
+
47
+ ### 2) 获取系统列表
48
+
49
+ ```bash
50
+ zt-zlp-cli discover systems
51
+ ```
52
+
53
+
54
+ ### 2) 获取服务列表
55
+
56
+ ```bash
57
+ zt-zlp-cli discover services --system LMS --log-type json
58
+ ```
59
+
60
+ ### 2.1) 日志搜索
61
+
62
+ ```bash
63
+ zt-zlp-cli discover logs \
64
+ --system LMS \
65
+ --service fbu-lms-labelservice-pro-json \
66
+ --log-type json \
67
+ --custom-sql "select topic,ClientIp,PrintMethod from \$table limit 10" \
68
+ --query-statement "SiteName = 'CN'" \
69
+ --start-time "2026-04-12 00:00:00" \
70
+ --end-time "2026-04-14 23:59:59"
71
+ ```
72
+
73
+ ## 全局参数
74
+ - `-o, --output`:输出格式,支持:
75
+ - `json`(默认)
76
+ - `human`(表格)
77
+
78
+ 示例:
79
+
80
+ ```bash
81
+ zt-zlp-cli -o human sql instances
82
+ ```
83
+
84
+ ## 配置说明
85
+
86
+ 默认配置目录:`~/.zt-zlp-cli`
87
+ - Cookie 缓存:`~/.zt-zlp-cli/cookies.json`
88
+ - 配置文件:`~/.zt-zlp-cli/config.yaml`
89
+
90
+ ## 环境变量(可选)
91
+
92
+ 支持通过环境变量自动填充登录页账号密码(如 SSO 页面字段可用):
93
+
94
+ - `ZT_SSO_USERNAME`
95
+ - `ZT_SSO_PASSWORD`
96
+
97
+ 未设置时可在浏览器中手动完成登录。
@@ -0,0 +1,13 @@
1
+ README.md
2
+ pyproject.toml
3
+ src/zt_zlp_cli/__init__.py
4
+ src/zt_zlp_cli/api.py
5
+ src/zt_zlp_cli/auth.py
6
+ src/zt_zlp_cli/cli.py
7
+ src/zt_zlp_cli/config.py
8
+ src/zt_zlp_cli.egg-info/PKG-INFO
9
+ src/zt_zlp_cli.egg-info/SOURCES.txt
10
+ src/zt_zlp_cli.egg-info/dependency_links.txt
11
+ src/zt_zlp_cli.egg-info/entry_points.txt
12
+ src/zt_zlp_cli.egg-info/requires.txt
13
+ src/zt_zlp_cli.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ zt-zlp-cli = zt_zlp_cli.cli:main
@@ -0,0 +1,4 @@
1
+ playwright>=1.40.0
2
+ requests>=2.31.0
3
+ click>=8.1.0
4
+ pyyaml>=6.0
@@ -0,0 +1 @@
1
+ zt_zlp_cli