Repository navigation
Expand file tree
/
Copy pathsysinfo.py
More file actions
executable file
·308 lines (258 loc) · 8.65 KB
/
Copy pathsysinfo.py
File metadata and controls
executable file
·308 lines (258 loc) · 8.65 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
#!/usr/bin/env python3
"""
sysinfo - 系统信息一览(Linux / Termux)
用法:
./sysinfo.py # 显示所有信息
./sysinfo.py -s cpu,mem,disk # 只看指定模块
./sysinfo.py --json # JSON 输出
可用模块: system, cpu, mem, disk, uptime, net, paths
依赖: 仅标准库
"""
import os
import sys
import json
import shutil
import platform
import socket
import unicodedata
from pathlib import Path
# ---------- 颜色 ----------
class C:
R = "\033[0m"
B = "\033[1m"
CYAN = "\033[36m"
GREEN = "\033[32m"
YELLOW = "\033[33m"
MAGENTA = "\033[35m"
RED = "\033[31m"
USE_COLOR = sys.stdout.isatty()
def color(text, c):
return f"{c}{text}{C.R}" if USE_COLOR else str(text)
# ---------- 显示宽度(处理中文对齐) ----------
def _wcwidth(ch):
return 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
def cwidth(s):
return sum(_wcwidth(c) for c in s)
def pad(s, width):
return s + " " * max(0, width - cwidth(s))
# ---------- 工具函数 ----------
def is_termux():
return os.environ.get("PREFIX", "").startswith("/data/data/com.termux")
def read_file(path, default=None):
try:
with open(path, "r", encoding="utf-8", errors="replace") as f:
return f.read().strip()
except OSError:
return default
def human_bytes(n):
n = float(n)
for unit in ("B", "K", "M", "G", "T", "P"):
if n < 1024:
return f"{n:.0f}{unit}" if unit == "B" else f"{n:.1f}{unit}"
n /= 1024
return f"{n:.1f}E"
def human_uptime(seconds):
seconds = int(seconds)
d, seconds = divmod(seconds, 86400)
h, seconds = divmod(seconds, 3600)
m, s = divmod(seconds, 60)
parts = []
if d: parts.append(f"{d}d")
if h: parts.append(f"{h}h")
if m: parts.append(f"{m}m")
if s and not parts: parts.append(f"{s}s")
return " ".join(parts) or "0s"
# ---------- 各模块 ----------
def info_system():
items = [
("主机名", socket.gethostname()),
("系统", f"{platform.system()} {platform.release()}"),
("版本", platform.version()),
("架构", platform.machine()),
("Python", f"{platform.python_version()} ({sys.executable})"),
]
if is_termux():
items.append(("环境", "Termux (Android)"))
build = read_file("/system/build.prop", "")
for line in build.splitlines():
if line.startswith("ro.build.version.release="):
items.append(("Android", line.split("=", 1)[1]))
elif line.startswith("ro.build.version.sdk="):
items.append(("SDK", line.split("=", 1)[1]))
return "系统", items
def info_cpu():
items = []
text = read_file("/proc/cpuinfo", "")
model = None
cores = 0
for line in text.splitlines():
if not model and (line.startswith("model name") or
line.startswith("Processor") or
line.startswith("Hardware")):
model = line.split(":", 1)[1].strip()
if line.startswith("processor"):
cores += 1
if model:
items.append(("型号", model))
if cores:
items.append(("核心数", str(cores)))
elif os.cpu_count():
items.append(("核心数", str(os.cpu_count())))
loadavg = read_file("/proc/loadavg", "")
if loadavg:
p = loadavg.split()
items.append(("负载", f"{p[0]} {p[1]} {p[2]}"))
return "CPU", items
def info_memory():
text = read_file("/proc/meminfo", "")
if not text:
return "内存", [("状态", "无法读取 /proc/meminfo")]
d = {}
for line in text.splitlines():
if ":" not in line:
continue
k, v = line.split(":", 1)
parts = v.strip().split()
if parts:
try:
d[k] = int(parts[0]) * 1024
except ValueError:
pass
total = d.get("MemTotal", 0)
avail = d.get("MemAvailable", d.get("MemFree", 0))
used = total - avail
items = []
if total:
items.append(("总计", human_bytes(total)))
items.append(("已用", human_bytes(used)))
items.append(("可用", human_bytes(avail)))
items.append(("使用率", f"{used / total * 100:.1f}%"))
swap_total = d.get("SwapTotal", 0)
if swap_total:
items.append(("Swap 总计", human_bytes(swap_total)))
items.append(("Swap 已用", human_bytes(swap_total - d.get("SwapFree", 0))))
return "内存", items
def info_disk():
items = []
paths = [("/", "根目录"), (os.path.expanduser("~"), "家目录")]
if is_termux() and os.path.isdir("/storage/emulated/0"):
paths.append(("/storage/emulated/0", "内部存储"))
seen = set()
for path, label in paths:
if path in seen or not os.path.isdir(path):
continue
seen.add(path)
try:
u = shutil.disk_usage(path)
pct = u.used / u.total * 100 if u.total else 0
items.append((label, f"{human_bytes(u.used)}/{human_bytes(u.total)} ({pct:.0f}%)"))
except OSError:
continue
return "磁盘", items
def info_uptime():
items = []
text = read_file("/proc/uptime", "")
if text:
p = text.split()
items.append(("运行时间", human_uptime(float(p[0]))))
if len(p) >= 2:
cpus = os.cpu_count() or 1
idle_pct = float(p[1]) / (float(p[0]) * cpus) * 100
items.append(("平均空闲率", f"{min(idle_pct, 100):.1f}%"))
return "运行时间", items
def info_network():
items = []
# 主 IP(UDP 技巧,不实际发包)
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.settimeout(0.5)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
if ip and ip != "0.0.0.0":
items.append(("主 IP", ip))
finally:
s.close()
except OSError:
pass
# 接口状态
netdir = Path("/sys/class/net")
if netdir.is_dir():
for iface in sorted(netdir.iterdir()):
if iface.name == "lo":
continue
try:
state = (iface / "operstate").read_text().strip()
mac = (iface / "address").read_text().strip()
if state == "up" or mac != "00:00:00:00:00:00":
items.append((iface.name, f"{mac} ({state})"))
except OSError:
continue
return "网络", items
def info_paths():
return "路径", [
("当前目录", os.getcwd()),
("家目录", os.path.expanduser("~")),
("PATH", os.environ.get("PATH", "?")),
]
MODULES = {
"system": info_system,
"cpu": info_cpu,
"mem": info_memory,
"disk": info_disk,
"uptime": info_uptime,
"net": info_network,
"paths": info_paths,
}
# ---------- 输出 ----------
def print_section(section, items):
print(color(f"━━ {section} ━━", C.CYAN + C.B))
for k, v in items:
ks = pad(str(k), 12)
vs = str(v)
if cwidth(vs) > 80:
print(f" {color(ks, C.YELLOW)} {vs}")
else:
print(f" {color(ks, C.YELLOW)} {vs}")
def to_json(selected):
out = {}
for name in selected:
_, items = MODULES[name]()
out[name] = {k: v for k, v in items}
return json.dumps(out, ensure_ascii=False, indent=2)
def main():
import argparse
parser = argparse.ArgumentParser(
description="查看系统信息(Linux / Termux)",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="可用模块: " + ", ".join(MODULES),
)
parser.add_argument("-s", "--sections", help="只显示指定模块,逗号分隔")
parser.add_argument("--json", action="store_true", help="JSON 输出")
parser.add_argument("--no-color", action="store_true", help="禁用颜色")
args = parser.parse_args()
global USE_COLOR
if args.no_color:
USE_COLOR = False
if args.sections:
selected = [s.strip() for s in args.sections.split(",") if s.strip()]
unknown = [s for s in selected if s not in MODULES]
if unknown:
print(f"未知模块: {', '.join(unknown)}", file=sys.stderr)
print(f"可用模块: {', '.join(MODULES)}", file=sys.stderr)
sys.exit(1)
else:
selected = list(MODULES)
if args.json:
print(to_json(selected))
return
print()
print(color(f" SysInfo @ {socket.gethostname()}", C.MAGENTA + C.B))
print()
for name in selected:
section, items = MODULES[name]()
if items:
print_section(section, items)
print()
if __name__ == "__main__":
main()