tplinkctl 0.1.0__py3-none-any.whl
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.
- tplinkctl/__init__.py +25 -0
- tplinkctl/__main__.py +7 -0
- tplinkctl/cli.py +413 -0
- tplinkctl/config.py +127 -0
- tplinkctl/diagnose.py +368 -0
- tplinkctl/endpoints.py +43 -0
- tplinkctl/errors.py +71 -0
- tplinkctl/router.py +275 -0
- tplinkctl-0.1.0.dist-info/METADATA +211 -0
- tplinkctl-0.1.0.dist-info/RECORD +13 -0
- tplinkctl-0.1.0.dist-info/WHEEL +4 -0
- tplinkctl-0.1.0.dist-info/entry_points.txt +2 -0
- tplinkctl-0.1.0.dist-info/licenses/LICENSE +674 -0
tplinkctl/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Amol Venkataraman
|
|
3
|
+
"""Read-first CLI and Python API for TP-Link routers, built on tplinkrouterc6u.
|
|
4
|
+
|
|
5
|
+
Provided AS IS, without warranty of any kind; see LICENSE and DISCLAIMER.md.
|
|
6
|
+
"""
|
|
7
|
+
__version__ = "0.1.0"
|
|
8
|
+
|
|
9
|
+
from .config import ConfigError, Settings, resolve_settings
|
|
10
|
+
from .diagnose import Finding, collect, diagnose
|
|
11
|
+
from .router import Router, RouterError, UnsupportedOperation, WriteNotAllowed
|
|
12
|
+
|
|
13
|
+
__all__ = [
|
|
14
|
+
"ConfigError",
|
|
15
|
+
"Finding",
|
|
16
|
+
"Router",
|
|
17
|
+
"RouterError",
|
|
18
|
+
"Settings",
|
|
19
|
+
"UnsupportedOperation",
|
|
20
|
+
"WriteNotAllowed",
|
|
21
|
+
"__version__",
|
|
22
|
+
"collect",
|
|
23
|
+
"diagnose",
|
|
24
|
+
"resolve_settings",
|
|
25
|
+
]
|
tplinkctl/__main__.py
ADDED
tplinkctl/cli.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Amol Venkataraman
|
|
3
|
+
"""`tplink` command-line interface. Run `tplink --help`."""
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import getpass
|
|
8
|
+
import ipaddress
|
|
9
|
+
import json
|
|
10
|
+
import logging
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import textwrap
|
|
14
|
+
from collections import defaultdict
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Any
|
|
17
|
+
|
|
18
|
+
import requests
|
|
19
|
+
|
|
20
|
+
from . import __version__
|
|
21
|
+
from .config import (
|
|
22
|
+
CONFIG_FILE,
|
|
23
|
+
DEFAULT_PASSWORD_FILE,
|
|
24
|
+
ConfigError,
|
|
25
|
+
resolve_host,
|
|
26
|
+
resolve_settings,
|
|
27
|
+
write_password_file,
|
|
28
|
+
)
|
|
29
|
+
from .diagnose import collect, diagnose
|
|
30
|
+
from .endpoints import discover_endpoints
|
|
31
|
+
from .errors import explain
|
|
32
|
+
from .router import WIFI_BANDS, Router, RouterError
|
|
33
|
+
|
|
34
|
+
GLOBAL_DEFAULTS: dict[str, Any] = {
|
|
35
|
+
"host": None, "username": None, "password_file": None, "timeout": None,
|
|
36
|
+
"insecure": False, "json": False, "debug": False, "config": str(CONFIG_FILE),
|
|
37
|
+
}
|
|
38
|
+
SEVERITY_MARK = {"error": "✖", "warn": "!", "info": "i", "ok": "✓"}
|
|
39
|
+
MAX_CELL = 48
|
|
40
|
+
WIFI_KEYS = ["ssid", "enable", "hidden", "encryption", "psk_version", "psk_key",
|
|
41
|
+
"channel", "current_channel", "htmode", "hwmode", "txpower"]
|
|
42
|
+
DISCLAIMER_SHORT = ("Provided AS IS, without warranty of any kind, under the GNU GPL v3 or later. "
|
|
43
|
+
"Written with AI assistance: review the code before running it. See DISCLAIMER.md.")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# --------------------------------------------------------------------------- output
|
|
47
|
+
|
|
48
|
+
def print_json(obj: Any) -> None:
|
|
49
|
+
print(json.dumps(obj, indent=2, default=str))
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def print_table(rows: list[dict[str, Any]], columns: list[str] | None = None) -> None:
|
|
53
|
+
if not rows:
|
|
54
|
+
print("(none)")
|
|
55
|
+
return
|
|
56
|
+
columns = columns or list(dict.fromkeys(k for row in rows for k in row))
|
|
57
|
+
|
|
58
|
+
def cell(value: Any) -> str:
|
|
59
|
+
text = "" if value is None else str(value)
|
|
60
|
+
return text if len(text) <= MAX_CELL else text[: MAX_CELL - 1] + "…"
|
|
61
|
+
|
|
62
|
+
table = [[cell(row.get(c)) for c in columns] for row in rows]
|
|
63
|
+
widths = [max(len(c), *(len(r[i]) for r in table)) for i, c in enumerate(columns)]
|
|
64
|
+
print(" ".join(c.upper().ljust(w) for c, w in zip(columns, widths, strict=True)).rstrip())
|
|
65
|
+
for r in table:
|
|
66
|
+
print(" ".join(v.ljust(w) for v, w in zip(r, widths, strict=True)).rstrip())
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def print_mapping(obj: dict[str, Any]) -> None:
|
|
70
|
+
width = max((len(k) for k in obj), default=0)
|
|
71
|
+
for k, v in obj.items():
|
|
72
|
+
print(f"{k.ljust(width)} {v}")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def emit(obj: Any, as_json: bool, columns: list[str] | None = None) -> None:
|
|
76
|
+
if as_json:
|
|
77
|
+
print_json(obj)
|
|
78
|
+
elif isinstance(obj, list):
|
|
79
|
+
print_table(obj, columns)
|
|
80
|
+
elif isinstance(obj, dict):
|
|
81
|
+
print_mapping(obj)
|
|
82
|
+
else:
|
|
83
|
+
print(obj)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def parse_params(pairs: list[str]) -> dict[str, str]:
|
|
87
|
+
params = {}
|
|
88
|
+
for pair in pairs:
|
|
89
|
+
key, sep, value = pair.partition("=")
|
|
90
|
+
if not sep or not key:
|
|
91
|
+
raise ValueError(f"parameter {pair!r} must look like key=value")
|
|
92
|
+
params[key] = value
|
|
93
|
+
return params
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def ip_sort_key(value: str) -> tuple[int, int]:
|
|
97
|
+
try:
|
|
98
|
+
return (0, int(ipaddress.IPv4Address(value)))
|
|
99
|
+
except ValueError:
|
|
100
|
+
return (1, 0)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# --------------------------------------------------------------------------- commands
|
|
104
|
+
|
|
105
|
+
def cmd_info(r: Router, a: argparse.Namespace) -> int:
|
|
106
|
+
emit({"client_type": r.client_type, **r.firmware()}, a.json)
|
|
107
|
+
return 0
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def cmd_status(r: Router, a: argparse.Namespace) -> int:
|
|
111
|
+
status = r.status()
|
|
112
|
+
devices = status.pop("devices", [])
|
|
113
|
+
if a.json:
|
|
114
|
+
print_json({**status, "devices_total": len(devices)})
|
|
115
|
+
else:
|
|
116
|
+
print_mapping({k: v for k, v in status.items() if v is not None})
|
|
117
|
+
return 0
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def cmd_devices(r: Router, a: argparse.Namespace) -> int:
|
|
121
|
+
columns = ["hostname", "ipaddr", "macaddr", "type", "signal", "down_speed", "up_speed", "online_time"]
|
|
122
|
+
emit(r.devices(), a.json, columns)
|
|
123
|
+
return 0
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def cmd_leases(r: Router, a: argparse.Namespace) -> int:
|
|
127
|
+
emit(r.leases(), a.json, ["hostname", "ipaddr", "macaddr", "lease_time"])
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def cmd_reservations(r: Router, a: argparse.Namespace) -> int:
|
|
132
|
+
emit(r.reservations(), a.json, ["hostname", "ipaddr", "macaddr", "enabled"])
|
|
133
|
+
return 0
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def cmd_arp(r: Router, a: argparse.Namespace) -> int:
|
|
137
|
+
arp = r.arp()
|
|
138
|
+
if not a.by_mac:
|
|
139
|
+
emit(arp, a.json, ["ipaddr", "mac", "name"])
|
|
140
|
+
return 0
|
|
141
|
+
groups: dict[str, list[str]] = defaultdict(list)
|
|
142
|
+
for entry in arp:
|
|
143
|
+
groups[entry.get("mac", "?")].append(entry.get("ipaddr", "?"))
|
|
144
|
+
rows = [{"mac": mac, "count": len(ips), "ips": " ".join(sorted(ips, key=ip_sort_key))}
|
|
145
|
+
for mac, ips in sorted(groups.items(), key=lambda kv: -len(kv[1]))]
|
|
146
|
+
if a.json:
|
|
147
|
+
print_json(rows)
|
|
148
|
+
else:
|
|
149
|
+
for row in rows:
|
|
150
|
+
print(f"{row['mac']} {row['count']:>4} {row['ips']}")
|
|
151
|
+
return 0
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def cmd_wifi(r: Router, a: argparse.Namespace) -> int:
|
|
155
|
+
wifi = r.wifi(show_secrets=a.show_secrets)
|
|
156
|
+
for band in wifi.get("ignored_bands", []):
|
|
157
|
+
print(f"note: the router returned placeholder settings for band {band} but has no such radio; ignored",
|
|
158
|
+
file=sys.stderr)
|
|
159
|
+
if a.json:
|
|
160
|
+
print_json(wifi)
|
|
161
|
+
return 0
|
|
162
|
+
for name, cfg in wifi.items():
|
|
163
|
+
if name == "ignored_bands":
|
|
164
|
+
continue
|
|
165
|
+
print(f"[{name}]")
|
|
166
|
+
print_mapping({k: cfg[k] for k in WIFI_KEYS if k in cfg} if name in WIFI_BANDS else cfg)
|
|
167
|
+
print()
|
|
168
|
+
return 0
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def cmd_logs(r: Router, a: argparse.Namespace) -> int:
|
|
172
|
+
logs = r.logs()
|
|
173
|
+
if a.type:
|
|
174
|
+
logs = [e for e in logs if str(e.get("type", "")).upper() == a.type.upper()]
|
|
175
|
+
if a.level:
|
|
176
|
+
logs = [e for e in logs if str(e.get("level", "")).upper() == a.level.upper()]
|
|
177
|
+
if a.grep:
|
|
178
|
+
logs = [e for e in logs if a.grep.lower() in str(e.get("content", "")).lower()]
|
|
179
|
+
logs = logs[: a.limit] if a.limit else logs
|
|
180
|
+
if a.json:
|
|
181
|
+
print_json(logs)
|
|
182
|
+
else:
|
|
183
|
+
for e in logs:
|
|
184
|
+
print(f"{e.get('time')} {e.get('level')!s:<7} {e.get('type')!s:<16} {e.get('content')}")
|
|
185
|
+
return 0
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _print_findings(findings, as_json: bool, show_ok: bool) -> None:
|
|
189
|
+
if as_json:
|
|
190
|
+
print_json([f.to_dict() for f in findings])
|
|
191
|
+
return
|
|
192
|
+
for f in findings:
|
|
193
|
+
if f.severity == "ok" and not show_ok:
|
|
194
|
+
continue
|
|
195
|
+
print(f"{SEVERITY_MARK.get(f.severity, '?')} [{f.severity}] {f.title}")
|
|
196
|
+
if f.detail:
|
|
197
|
+
print(f" {f.detail}")
|
|
198
|
+
counts = {s: sum(f.severity == s for f in findings) for s in ("error", "warn", "info", "ok")}
|
|
199
|
+
print(f"\n{counts['error']} error(s), {counts['warn']} warning(s), {counts['info']} note(s), {counts['ok']} passed")
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def cmd_diagnose(r: Router | None, a: argparse.Namespace) -> int:
|
|
203
|
+
if a.from_file:
|
|
204
|
+
snapshot = json.loads(Path(a.from_file).read_text())
|
|
205
|
+
else:
|
|
206
|
+
snapshot = collect(r, probe_dns=a.probe_dns)
|
|
207
|
+
if a.save:
|
|
208
|
+
Path(a.save).write_text(json.dumps(snapshot, indent=2, default=str))
|
|
209
|
+
print(f"snapshot saved to {a.save}", file=sys.stderr)
|
|
210
|
+
findings = diagnose(snapshot, hoard_threshold=a.hoard_threshold)
|
|
211
|
+
_print_findings(findings, a.json, a.verbose)
|
|
212
|
+
return 1 if any(f.severity == "error" for f in findings) else 0
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def cmd_snapshot(r: Router, a: argparse.Namespace) -> int:
|
|
216
|
+
text = json.dumps(collect(r, probe_dns=a.probe_dns), indent=2, default=str)
|
|
217
|
+
if a.output:
|
|
218
|
+
Path(a.output).write_text(text)
|
|
219
|
+
print(f"snapshot saved to {a.output}", file=sys.stderr)
|
|
220
|
+
else:
|
|
221
|
+
print(text)
|
|
222
|
+
return 0
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def cmd_read(r: Router, a: argparse.Namespace) -> int:
|
|
226
|
+
result = r.request(a.path, a.op, a.param_dict) if a.op else r.read(a.path, a.param_dict)
|
|
227
|
+
print_json(result)
|
|
228
|
+
return 0
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def cmd_write(r: Router, a: argparse.Namespace) -> int:
|
|
232
|
+
if not a.yes:
|
|
233
|
+
print(f"About to send operation={a.op} to {a.path} with {a.param_dict or 'no parameters'}.")
|
|
234
|
+
if input("This changes router settings. Type 'yes' to continue: ").strip().lower() != "yes":
|
|
235
|
+
print("aborted")
|
|
236
|
+
return 1
|
|
237
|
+
print_json(r.request(a.path, a.op, a.param_dict, allow_write=True))
|
|
238
|
+
return 0
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
# --------------------------------------------------------------------------- parser
|
|
242
|
+
|
|
243
|
+
def _add_global_options(p: argparse.ArgumentParser) -> None:
|
|
244
|
+
S = argparse.SUPPRESS # so options work both before and after the subcommand
|
|
245
|
+
g = p.add_argument_group("connection/output")
|
|
246
|
+
g.add_argument("--host", default=S, help="router URL or IP (default: config, $TPLINK_HOST, http://192.168.0.1)")
|
|
247
|
+
g.add_argument("--username", default=S, help="admin username (default: admin)")
|
|
248
|
+
g.add_argument("--password-file", default=S,
|
|
249
|
+
help="file whose first line is the password (default: ~/.config/tplinkctl/password)")
|
|
250
|
+
g.add_argument("--timeout", type=int, default=S, help="request timeout in seconds (default: 30)")
|
|
251
|
+
g.add_argument("--insecure", action="store_true", default=S, help="don't verify HTTPS certificates")
|
|
252
|
+
g.add_argument("--config", default=S, help="config file (default: ~/.config/tplinkctl/config.ini)")
|
|
253
|
+
g.add_argument("--json", action="store_true", default=S, help="machine-readable JSON output")
|
|
254
|
+
g.add_argument("--debug", action="store_true", default=S, help="log HTTP-level details and raw errors to stderr")
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
258
|
+
parser = argparse.ArgumentParser(
|
|
259
|
+
prog="tplink",
|
|
260
|
+
description="Read-first CLI for TP-Link routers. Nothing is changed unless you use `write`.",
|
|
261
|
+
epilog=textwrap.fill("Password: put it in ~/.config/tplinkctl/password (run `tplink set-password`) "
|
|
262
|
+
"or set $TPLINK_PASSWORD.") + "\n\n" + textwrap.fill(DISCLAIMER_SHORT),
|
|
263
|
+
formatter_class=argparse.RawDescriptionHelpFormatter)
|
|
264
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}\n{textwrap.fill(DISCLAIMER_SHORT)}")
|
|
265
|
+
_add_global_options(parser)
|
|
266
|
+
sub = parser.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
267
|
+
|
|
268
|
+
def add(name: str, func, help_text: str, login: bool = True) -> argparse.ArgumentParser:
|
|
269
|
+
p = sub.add_parser(name, help=help_text, description=help_text)
|
|
270
|
+
_add_global_options(p)
|
|
271
|
+
p.set_defaults(func=func, login=login)
|
|
272
|
+
return p
|
|
273
|
+
|
|
274
|
+
add("info", cmd_info, "model, firmware and detected client type")
|
|
275
|
+
add("status", cmd_status, "WAN/LAN/Wi-Fi status summary")
|
|
276
|
+
add("devices", cmd_devices, "connected clients")
|
|
277
|
+
add("leases", cmd_leases, "DHCP leases")
|
|
278
|
+
add("reservations", cmd_reservations, "DHCP address reservations")
|
|
279
|
+
|
|
280
|
+
p = add("arp", cmd_arp, "router ARP table (which MAC answers for which IP)")
|
|
281
|
+
p.add_argument("--by-mac", action="store_true", help="group IPs by MAC (spots devices claiming many IPs)")
|
|
282
|
+
|
|
283
|
+
p = add("wifi", cmd_wifi, "Wi-Fi settings per band (passwords redacted)")
|
|
284
|
+
p.add_argument("--show-secrets", action="store_true", help="include Wi-Fi passwords")
|
|
285
|
+
|
|
286
|
+
p = add("logs", cmd_logs, "router system log")
|
|
287
|
+
p.add_argument("-n", "--limit", type=int, default=50, help="max entries, newest first (0 = all; default 50)")
|
|
288
|
+
p.add_argument("--type", help="only this log type, e.g. DHCPC, NAT")
|
|
289
|
+
p.add_argument("--level", help="only this level, e.g. WARNING")
|
|
290
|
+
p.add_argument("--grep", help="only entries containing this text")
|
|
291
|
+
|
|
292
|
+
p = add("diagnose", cmd_diagnose, "check for common reasons devices can't connect")
|
|
293
|
+
p.add_argument("--from", dest="from_file", metavar="FILE", help="diagnose a saved snapshot instead of the live router")
|
|
294
|
+
p.add_argument("--save", metavar="FILE", help="also save the collected snapshot as JSON")
|
|
295
|
+
p.add_argument("--probe-dns", action="store_true", help="test the DNS servers DHCP hands out (from this machine)")
|
|
296
|
+
p.add_argument("--hoard-threshold", type=int, default=3, help="flag a MAC answering for this many IPs (default 3)")
|
|
297
|
+
p.add_argument("-v", "--verbose", action="store_true", help="also show passed checks")
|
|
298
|
+
|
|
299
|
+
p = add("snapshot", cmd_snapshot, "dump everything diagnose reads as JSON (secrets redacted)")
|
|
300
|
+
p.add_argument("-o", "--output", metavar="FILE", help="write to FILE instead of stdout")
|
|
301
|
+
p.add_argument("--probe-dns", action="store_true", help="include a DNS reachability probe")
|
|
302
|
+
|
|
303
|
+
p = add("read", cmd_read, "read any endpoint, e.g. 'admin/dhcps?form=setting' (see `endpoints`)")
|
|
304
|
+
p.add_argument("path")
|
|
305
|
+
p.add_argument("params", nargs="*", metavar="key=value", help="extra request parameters")
|
|
306
|
+
p.add_argument("--op", choices=["read", "load"], help="operation (default: try read, then load)")
|
|
307
|
+
|
|
308
|
+
p = add("write", cmd_write, "send a state-changing operation to an endpoint (asks for confirmation)")
|
|
309
|
+
p.add_argument("path")
|
|
310
|
+
p.add_argument("params", nargs="*", metavar="key=value", help="request parameters")
|
|
311
|
+
p.add_argument("--op", required=True, help="operation, e.g. write, insert, remove")
|
|
312
|
+
p.add_argument("-y", "--yes", action="store_true", help="skip the confirmation prompt")
|
|
313
|
+
|
|
314
|
+
p = add("endpoints", None, "list endpoints found in the router's web UI (no login)", login=False)
|
|
315
|
+
p.add_argument("--grep", help="only endpoints containing this text")
|
|
316
|
+
|
|
317
|
+
p = add("set-password", None, "save the router password to the password file (mode 600)", login=False)
|
|
318
|
+
p.add_argument("--file", default=str(DEFAULT_PASSWORD_FILE),
|
|
319
|
+
help="where to store it (default: ~/.config/tplinkctl/password)")
|
|
320
|
+
return parser
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
|
|
324
|
+
"""Parse and validate everything that can be checked before logging in.
|
|
325
|
+
|
|
326
|
+
Logging in kicks other admin sessions and counts toward the router's
|
|
327
|
+
lockout, so bad input is rejected first.
|
|
328
|
+
"""
|
|
329
|
+
parser = build_parser()
|
|
330
|
+
args, extra = parser.parse_known_args(argv)
|
|
331
|
+
# argparse can't take positionals after options (`write PATH --op write a=1`), so
|
|
332
|
+
# trailing key=value tokens are folded into params for read/write.
|
|
333
|
+
if extra and getattr(args, "params", None) is not None and all("=" in x and not x.startswith("-") for x in extra):
|
|
334
|
+
args.params += extra
|
|
335
|
+
elif extra:
|
|
336
|
+
parser.error(f"unrecognized arguments: {' '.join(extra)}")
|
|
337
|
+
for name, default in GLOBAL_DEFAULTS.items():
|
|
338
|
+
if not hasattr(args, name):
|
|
339
|
+
setattr(args, name, default)
|
|
340
|
+
if getattr(args, "params", None) is not None:
|
|
341
|
+
try:
|
|
342
|
+
args.param_dict = parse_params(args.params)
|
|
343
|
+
except ValueError as e:
|
|
344
|
+
parser.error(str(e))
|
|
345
|
+
if args.command == "write" and not args.yes and not sys.stdin.isatty():
|
|
346
|
+
parser.error("refusing to write without --yes when not running interactively")
|
|
347
|
+
return args
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def _run(args: argparse.Namespace, logger: logging.Logger | None) -> int:
|
|
351
|
+
if args.command == "set-password":
|
|
352
|
+
first = getpass.getpass("Router admin password: ")
|
|
353
|
+
if not first or first != getpass.getpass("Again: "):
|
|
354
|
+
print("error: passwords empty or did not match", file=sys.stderr)
|
|
355
|
+
return 2
|
|
356
|
+
print(f"saved to {write_password_file(first, args.file)}")
|
|
357
|
+
return 0
|
|
358
|
+
|
|
359
|
+
if args.command == "endpoints":
|
|
360
|
+
host = resolve_host(args.host, args.config)
|
|
361
|
+
try:
|
|
362
|
+
found = discover_endpoints(host, timeout=args.timeout or 10, verify_ssl=not args.insecure)
|
|
363
|
+
except requests.RequestException as e:
|
|
364
|
+
raise RouterError(explain(e, host=host), e) from e
|
|
365
|
+
if args.grep:
|
|
366
|
+
found = [e for e in found if args.grep in e]
|
|
367
|
+
if args.json:
|
|
368
|
+
print_json(found)
|
|
369
|
+
else:
|
|
370
|
+
print("\n".join(found) or "(none found)")
|
|
371
|
+
return 0
|
|
372
|
+
|
|
373
|
+
if args.command == "diagnose" and args.from_file:
|
|
374
|
+
return cmd_diagnose(None, args)
|
|
375
|
+
|
|
376
|
+
settings = resolve_settings(args.host, args.username, args.password_file, args.timeout,
|
|
377
|
+
args.insecure, args.config)
|
|
378
|
+
with Router.from_settings(settings, logger) as router:
|
|
379
|
+
return args.func(router, args)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def main(argv: list[str] | None = None) -> int:
|
|
383
|
+
args = parse_args(argv)
|
|
384
|
+
logging.basicConfig(level=logging.DEBUG if args.debug else logging.WARNING,
|
|
385
|
+
format="%(levelname)s %(name)s: %(message)s")
|
|
386
|
+
logger = logging.getLogger("tplinkctl") if args.debug else None
|
|
387
|
+
try:
|
|
388
|
+
code = _run(args, logger)
|
|
389
|
+
sys.stdout.flush() # surface a closed pipe here rather than during interpreter shutdown
|
|
390
|
+
return code
|
|
391
|
+
except ConfigError as e:
|
|
392
|
+
print(f"error: {e}", file=sys.stderr)
|
|
393
|
+
return 2
|
|
394
|
+
except RouterError as e:
|
|
395
|
+
print(f"error: {e}", file=sys.stderr)
|
|
396
|
+
if args.debug and e.raw is not None:
|
|
397
|
+
print(f"raw error: {e.raw!r}", file=sys.stderr)
|
|
398
|
+
return 1
|
|
399
|
+
except BrokenPipeError: # output piped into e.g. `head`, which exited early
|
|
400
|
+
devnull = os.open(os.devnull, os.O_WRONLY)
|
|
401
|
+
os.dup2(devnull, sys.stdout.fileno())
|
|
402
|
+
return 0
|
|
403
|
+
except KeyboardInterrupt:
|
|
404
|
+
return 130
|
|
405
|
+
except Exception as e:
|
|
406
|
+
if args.debug:
|
|
407
|
+
raise
|
|
408
|
+
print(f"error: {type(e).__name__}: {e} (re-run with --debug for details)", file=sys.stderr)
|
|
409
|
+
return 1
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
if __name__ == "__main__":
|
|
413
|
+
sys.exit(main())
|
tplinkctl/config.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
2
|
+
# Copyright (C) 2026 Amol Venkataraman
|
|
3
|
+
"""Resolve router connection settings from CLI flags, environment and config file.
|
|
4
|
+
|
|
5
|
+
Precedence (highest first): explicit arguments, environment variables, the
|
|
6
|
+
config file (~/.config/tplinkctl/config.ini), built-in defaults.
|
|
7
|
+
|
|
8
|
+
The password is never taken from a command-line flag (it would leak into shell
|
|
9
|
+
history and `ps`). It comes from, in order: TPLINK_PASSWORD, a password file
|
|
10
|
+
named by --password-file / TPLINK_PASSWORD_FILE / the config file, or the
|
|
11
|
+
default password file ~/.config/tplinkctl/password.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import configparser
|
|
16
|
+
import os
|
|
17
|
+
import stat
|
|
18
|
+
import sys
|
|
19
|
+
from collections.abc import Mapping
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
|
|
23
|
+
CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "tplinkctl"
|
|
24
|
+
CONFIG_FILE = CONFIG_DIR / "config.ini"
|
|
25
|
+
DEFAULT_PASSWORD_FILE = CONFIG_DIR / "password"
|
|
26
|
+
DEFAULT_HOST = "http://192.168.0.1"
|
|
27
|
+
DEFAULT_USERNAME = "admin"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class ConfigError(Exception):
|
|
31
|
+
"""Settings could not be resolved (missing/empty password file, bad config)."""
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@dataclass(frozen=True)
|
|
35
|
+
class Settings:
|
|
36
|
+
host: str
|
|
37
|
+
username: str
|
|
38
|
+
password: str
|
|
39
|
+
timeout: int = 30
|
|
40
|
+
verify_ssl: bool = True
|
|
41
|
+
|
|
42
|
+
def __repr__(self) -> str: # keep the password out of logs and tracebacks
|
|
43
|
+
return (f"Settings(host={self.host!r}, username={self.username!r}, password='***', "
|
|
44
|
+
f"timeout={self.timeout}, verify_ssl={self.verify_ssl})")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def normalize_host(host: str) -> str:
|
|
48
|
+
host = host.strip().rstrip("/")
|
|
49
|
+
return host if "://" in host else f"http://{host}"
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def read_password_file(path: str | Path) -> str:
|
|
53
|
+
"""Return the first line of `path`, warning if other users can read it."""
|
|
54
|
+
path = Path(path).expanduser()
|
|
55
|
+
try:
|
|
56
|
+
text = path.read_text(encoding="utf-8")
|
|
57
|
+
except FileNotFoundError:
|
|
58
|
+
raise ConfigError(f"password file not found: {path} (create it with `tplink set-password`)") from None
|
|
59
|
+
except OSError as e:
|
|
60
|
+
raise ConfigError(f"cannot read password file {path}: {e}") from None
|
|
61
|
+
if path.stat().st_mode & (stat.S_IRWXG | stat.S_IRWXO):
|
|
62
|
+
print(f"warning: {path} is accessible by other users; run: chmod 600 {path}", file=sys.stderr)
|
|
63
|
+
lines = text.splitlines()
|
|
64
|
+
password = lines[0] if lines else ""
|
|
65
|
+
if not password:
|
|
66
|
+
raise ConfigError(f"password file is empty: {path}")
|
|
67
|
+
return password
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def write_password_file(password: str, path: str | Path = DEFAULT_PASSWORD_FILE) -> Path:
|
|
71
|
+
"""Store `password` in `path` with mode 0600 (directory 0700)."""
|
|
72
|
+
path = Path(path).expanduser()
|
|
73
|
+
path.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
74
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
75
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
76
|
+
f.write(password + "\n")
|
|
77
|
+
os.chmod(path, 0o600) # O_CREAT's mode is ignored if the file already existed
|
|
78
|
+
return path
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def load_config_file(path: str | Path = CONFIG_FILE) -> dict[str, str]:
|
|
82
|
+
"""Return the [router] section of the INI config file, or {} if absent."""
|
|
83
|
+
path = Path(path).expanduser()
|
|
84
|
+
if not path.exists():
|
|
85
|
+
return {}
|
|
86
|
+
parser = configparser.ConfigParser()
|
|
87
|
+
try:
|
|
88
|
+
parser.read(path, encoding="utf-8")
|
|
89
|
+
except configparser.Error as e:
|
|
90
|
+
raise ConfigError(f"invalid config file {path}: {e}") from None
|
|
91
|
+
return dict(parser["router"]) if parser.has_section("router") else {}
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def resolve_host(host: str | None = None, config_file: str | Path = CONFIG_FILE,
|
|
95
|
+
env: Mapping[str, str] = os.environ) -> str:
|
|
96
|
+
"""Resolve only the host (for commands that don't log in)."""
|
|
97
|
+
return normalize_host(host or env.get("TPLINK_HOST") or load_config_file(config_file).get("host") or DEFAULT_HOST)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def resolve_settings(
|
|
101
|
+
host: str | None = None,
|
|
102
|
+
username: str | None = None,
|
|
103
|
+
password_file: str | Path | None = None,
|
|
104
|
+
timeout: int | None = None,
|
|
105
|
+
insecure: bool = False,
|
|
106
|
+
config_file: str | Path = CONFIG_FILE,
|
|
107
|
+
env: Mapping[str, str] = os.environ,
|
|
108
|
+
) -> Settings:
|
|
109
|
+
cfg = load_config_file(config_file)
|
|
110
|
+
|
|
111
|
+
host = resolve_host(host, config_file, env)
|
|
112
|
+
username = username or env.get("TPLINK_USERNAME") or cfg.get("username") or DEFAULT_USERNAME
|
|
113
|
+
|
|
114
|
+
if password_file is None and env.get("TPLINK_PASSWORD"):
|
|
115
|
+
password = env["TPLINK_PASSWORD"]
|
|
116
|
+
else:
|
|
117
|
+
source = password_file or env.get("TPLINK_PASSWORD_FILE") or cfg.get("password_file") or DEFAULT_PASSWORD_FILE
|
|
118
|
+
password = read_password_file(source)
|
|
119
|
+
|
|
120
|
+
if timeout is None:
|
|
121
|
+
try:
|
|
122
|
+
timeout = int(env.get("TPLINK_TIMEOUT") or cfg.get("timeout") or 30)
|
|
123
|
+
except ValueError:
|
|
124
|
+
raise ConfigError("timeout must be an integer number of seconds") from None
|
|
125
|
+
|
|
126
|
+
verify_ssl = not insecure and cfg.get("verify_ssl", "true").strip().lower() not in {"0", "false", "no", "off"}
|
|
127
|
+
return Settings(host, username, password, timeout, verify_ssl)
|