iptime-cli 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.
iptime_cli/client.py ADDED
@@ -0,0 +1,495 @@
1
+ """HTTP client and typed helpers for the ipTIME JSON API (new admin UI, firmware 16.x)."""
2
+ from __future__ import annotations
3
+
4
+ import http.client
5
+ import http.cookiejar
6
+ import json
7
+ import re
8
+ import ssl
9
+ import time
10
+ import urllib.error
11
+ import urllib.request
12
+ from dataclasses import asdict, dataclass, field
13
+ from typing import Any, Optional
14
+
15
+ from .catalog import classify
16
+
17
+ MAC_RE = re.compile(r"^[0-9A-Fa-f]{2}([:-][0-9A-Fa-f]{2}){5}$")
18
+
19
+
20
+ class IptimeError(Exception):
21
+ """Base class for every error this package raises."""
22
+
23
+
24
+ class ConnectError(IptimeError):
25
+ """The router could not be reached."""
26
+
27
+
28
+ class OldUiError(IptimeError):
29
+ """The router serves the old admin UI, which this package does not support yet."""
30
+
31
+
32
+ class LoginError(IptimeError):
33
+ """The router refused the login."""
34
+
35
+
36
+ class CaptchaError(LoginError):
37
+ """The router wants a captcha before it accepts another login."""
38
+
39
+
40
+ class LockoutError(LoginError):
41
+ """The router temporarily blocks logins (too many failures)."""
42
+
43
+
44
+ class UpgradeError(IptimeError):
45
+ """The firmware upgrade failed, timed out or never started."""
46
+
47
+
48
+ class ApiError(IptimeError):
49
+ """The router answered a call with an error object."""
50
+
51
+ def __init__(self, method: str, code: Any, message: str):
52
+ super().__init__(f"{method}: {message} (code {code})")
53
+ self.method, self.code, self.message = method, code, message
54
+
55
+
56
+ def normalize_host(host: str) -> str:
57
+ """``192.168.0.1``, ``192.168.0.1:8080`` or a full URL -> ``http://host[:port]``."""
58
+ host = (host or "").strip().rstrip("/")
59
+ if not host:
60
+ raise IptimeError("no router address: pass --host or set IPTIME_HOST")
61
+ if "://" not in host:
62
+ host = "http://" + host
63
+ if host.endswith("/ui"):
64
+ host = host[:-3]
65
+ return host
66
+
67
+
68
+ def normalize_mac(mac: str) -> str:
69
+ if not MAC_RE.match(mac or ""):
70
+ raise IptimeError(f"not a MAC address: {mac!r} (expected AA:BB:CC:00:00:01)")
71
+ return mac.replace("-", ":").upper()
72
+
73
+
74
+ def parse_ports(text: str) -> dict:
75
+ """``8080`` -> {"start": 8080}; ``8000-8010`` -> {"start": 8000, "end": 8010}."""
76
+ m = re.fullmatch(r"\s*(\d{1,5})(?:\s*-\s*(\d{1,5}))?\s*", str(text))
77
+ if not m:
78
+ raise IptimeError(f"not a port or port range: {text!r}")
79
+ start = int(m.group(1))
80
+ out = {"start": start}
81
+ if m.group(2):
82
+ end = int(m.group(2))
83
+ if end < start:
84
+ raise IptimeError(f"port range ends before it starts: {text!r}")
85
+ out["end"] = end
86
+ for value in out.values():
87
+ if not 1 <= value <= 65535:
88
+ raise IptimeError(f"port out of range 1-65535: {text!r}")
89
+ return out
90
+
91
+
92
+ @dataclass
93
+ class Station:
94
+ """One device the router sees (wired or Wi-Fi)."""
95
+ mac: str
96
+ ip: str = ""
97
+ name: str = ""
98
+ link: str = "" # "wired" or "wireless"
99
+ where: str = "" # LAN port ("lan2") or BSS ("5g.1")
100
+ rssi: Optional[int] = None
101
+ down_mbps: Optional[int] = None
102
+ up_mbps: Optional[int] = None
103
+ down_bytes: Optional[int] = None
104
+ up_bytes: Optional[int] = None
105
+ addressing: str = "" # "dhcp" or "static"
106
+ lease_remaining: Optional[int] = None
107
+ reserved: bool = False
108
+
109
+ def as_dict(self) -> dict:
110
+ return asdict(self)
111
+
112
+
113
+ @dataclass
114
+ class Lease:
115
+ mac: str
116
+ ip: str
117
+ remaining: int = 0
118
+ name: str = ""
119
+
120
+
121
+ @dataclass
122
+ class Reservation:
123
+ mac: str
124
+ ip: str
125
+ name: str = ""
126
+
127
+
128
+ @dataclass
129
+ class PortForward:
130
+ name: str
131
+ protocol: str
132
+ target: str
133
+ external: dict = field(default_factory=dict) # "src" in the API
134
+ internal: dict = field(default_factory=dict) # "dst" in the API
135
+ active: bool = True
136
+ fixed: bool = False
137
+
138
+ @staticmethod
139
+ def span(ports: dict) -> str:
140
+ if not ports:
141
+ return ""
142
+ if "end" in ports and ports["end"] != ports["start"]:
143
+ return f"{ports['start']}-{ports['end']}"
144
+ return str(ports["start"])
145
+
146
+ def as_dict(self) -> dict:
147
+ d = asdict(self)
148
+ d["external"], d["internal"] = self.span(self.external), self.span(self.internal)
149
+ return d
150
+
151
+
152
+ class Router:
153
+ """Talk to one router. Logs in lazily on the first call.
154
+
155
+ ``dry_run=True`` makes every call that is not a read return the request instead of sending it.
156
+ Logging in may end an admin session that is open in a browser.
157
+ """
158
+
159
+ def __init__(self, host: str, user: str = "admin", password: str = "", *, timeout: float = 15,
160
+ verify_tls: bool = True, dry_run: bool = False):
161
+ self.base = normalize_host(host)
162
+ self.user, self.password = user, password
163
+ self.timeout, self.dry_run = timeout, dry_run
164
+ self.logged_in = False
165
+ self.sent: list = [] # every request that went to /cgi/service.cgi (without secrets)
166
+ handlers: list = [urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())]
167
+ if self.base.startswith("https") and not verify_tls:
168
+ ctx = ssl.create_default_context()
169
+ ctx.check_hostname, ctx.verify_mode = False, ssl.CERT_NONE
170
+ handlers.append(urllib.request.HTTPSHandler(context=ctx))
171
+ self._opener = urllib.request.build_opener(*handlers)
172
+
173
+ # -- plumbing ---------------------------------------------------------------------------
174
+ def __enter__(self) -> "Router":
175
+ return self
176
+
177
+ def __exit__(self, *exc) -> None:
178
+ self.close()
179
+
180
+ def close(self) -> None:
181
+ """Log out (best effort)."""
182
+ if self.logged_in:
183
+ try:
184
+ self._post({"method": "session/logout"})
185
+ except IptimeError:
186
+ pass
187
+ self.logged_in = False
188
+
189
+ def _open(self, req):
190
+ try:
191
+ return self._opener.open(req, timeout=self.timeout)
192
+ except urllib.error.HTTPError as exc:
193
+ return exc
194
+ except (urllib.error.URLError, OSError, http.client.HTTPException) as exc:
195
+ raise ConnectError(f"cannot reach {self.base}: {getattr(exc, 'reason', exc)}") from exc
196
+
197
+ def _post(self, body: dict) -> dict:
198
+ req = urllib.request.Request(
199
+ self.base + "/cgi/service.cgi", json.dumps(body).encode(),
200
+ {"Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store",
201
+ "Origin": self.base, "Referer": self.base + "/ui/"})
202
+ resp = self._open(req)
203
+ raw = resp.read()
204
+ try:
205
+ data = json.loads(raw)
206
+ except ValueError:
207
+ raise OldUiError(
208
+ "old admin UI not supported yet: /cgi/service.cgi did not answer JSON "
209
+ f"(HTTP {getattr(resp, 'status', '?')}). Only the new admin UI (firmware 16.x, "
210
+ "served at /ui/) is supported.") from None
211
+ if not isinstance(data, dict):
212
+ raise IptimeError(f"unexpected answer from the router: {raw[:80]!r}")
213
+ return data
214
+
215
+ def request_for(self, method: str, params: Any = None) -> dict:
216
+ body: dict = {"method": method}
217
+ if params is not None:
218
+ body["params"] = params
219
+ return body
220
+
221
+ def connect(self) -> None:
222
+ """Fetch the admin UI once (sets the cookie) and refuse the old admin UI."""
223
+ resp = self._open(urllib.request.Request(self.base + "/ui/"))
224
+ page = resp.read(65536).decode("utf-8", "replace")
225
+ status = getattr(resp, "status", 200)
226
+ if status != 200 or "flutter" not in page.lower():
227
+ raise OldUiError(
228
+ "old admin UI not supported yet: no new admin UI at "
229
+ f"{self.base}/ui/ (HTTP {status}). This package needs firmware 16.x.")
230
+
231
+ def login(self) -> None:
232
+ if self.logged_in:
233
+ return
234
+ if not self.password:
235
+ raise LoginError("no password given")
236
+ self.connect()
237
+ data = self._post({"method": "session/login",
238
+ "params": {"id": self.user, "pw": self.password}})
239
+ if data.get("result") == "done":
240
+ self.logged_in = True
241
+ return
242
+ text = json.dumps(data, ensure_ascii=False)
243
+ low = text.lower()
244
+ if "captcha" in low:
245
+ raise CaptchaError(f"the router asks for a captcha before the next login: {text}")
246
+ if any(w in low for w in ("lock", "block", "too many", "wait")):
247
+ raise LockoutError(f"the router blocks logins for now: {text}")
248
+ hint = " (wrong user or password?)" if (data.get("error") or {}).get("code") == -31996 else ""
249
+ raise LoginError(f"login failed{hint}: {text}")
250
+
251
+ # -- calls ------------------------------------------------------------------------------
252
+ def call_raw(self, method: str, params: Any = None) -> dict:
253
+ """Send one call and return the whole answer ({"result": ..., "error": ...})."""
254
+ body = self.request_for(method, params)
255
+ if self.dry_run and classify(method, params) in ("write", "danger"):
256
+ return {"dry_run": True, "would_send": {"POST": self.base + "/cgi/service.cgi",
257
+ "body": body}}
258
+ self.login()
259
+ data = self._post(body)
260
+ if (data.get("error") or {}).get("message") == "Unauthenticated" and method != "session/login":
261
+ self.logged_in = False # session expired: log in once more and retry
262
+ self.login()
263
+ data = self._post(body)
264
+ self.sent.append(body)
265
+ return data
266
+
267
+ def call(self, method: str, params: Any = None) -> Any:
268
+ """Send one call and return ``result``; raise :class:`ApiError` on an error object."""
269
+ data = self.call_raw(method, params)
270
+ if data.get("dry_run"):
271
+ return data
272
+ err = data.get("error")
273
+ if err:
274
+ raise ApiError(method, err.get("code"), err.get("message", "error"))
275
+ return data.get("result")
276
+
277
+ def has_method(self, method: str) -> bool:
278
+ return bool(self.call("api/has", method))
279
+
280
+ # -- reads ------------------------------------------------------------------------------
281
+ def session(self) -> dict:
282
+ return self.call("session/info")
283
+
284
+ def product(self) -> dict:
285
+ return self.call("product/info")
286
+
287
+ def firmware(self) -> dict:
288
+ info = self.call("firmware/info")
289
+ try:
290
+ latest = self.call("firmware/version/latest")
291
+ except ApiError:
292
+ latest = None
293
+ info["latest"] = latest
294
+ info["update_available"] = bool(latest) and _version_key(str(latest)) > _version_key(
295
+ str(info.get("version", "0")))
296
+ return info
297
+
298
+ def system(self, secrets: bool = False) -> dict:
299
+ data = self.call("system/info")
300
+ if not secrets:
301
+ data = _mask(data)
302
+ return data
303
+
304
+ def wan(self) -> dict:
305
+ info = self.call("network/interface/wan1/info")
306
+ info["dns"] = _try(self, "network/dns/info")
307
+ for port in _try(self, "port/link/status") or []:
308
+ if port.get("type") == "wan":
309
+ info["link_speed"] = port.get("link")
310
+ for stat in _try(self, "port/stat/get") or []:
311
+ if stat.get("type") == "wan":
312
+ info["rx_bytes"] = stat.get("rx", {}).get("byte")
313
+ info["tx_bytes"] = stat.get("tx", {}).get("byte")
314
+ return info
315
+
316
+ def lan(self) -> dict:
317
+ info = self.call("network/interface/lan/info")
318
+ info["dhcp"] = _try(self, "dhcpd/config/get", "lan")
319
+ return info
320
+
321
+ def leases(self) -> list:
322
+ return [Lease(x["mac"].upper(), x.get("ip", ""), x.get("remaining", 0), x.get("desc", ""))
323
+ for x in self.call("dhcpd/lease/show", "lan") or []]
324
+
325
+ def reservations(self) -> list:
326
+ return [Reservation(x["mac"].upper(), x.get("ip", ""), x.get("desc", ""))
327
+ for x in self.call("dhcpd/reservedaddr/show", "lan") or []]
328
+
329
+ def stations(self) -> list:
330
+ """All devices the router sees, merged with DHCP leases and reservations."""
331
+ leases = {x.mac: x for x in self.leases()}
332
+ reserved = {x.mac for x in self.reservations()}
333
+ out = []
334
+ for item in self.call("network/interface/lan/stations") or []:
335
+ info, conn = item.get("info") or {}, item.get("connection") or {}
336
+ mac = item["mac"].upper()
337
+ kind = conn.get("type", "")
338
+ detail = conn.get(kind) or {}
339
+ st = Station(mac=mac, ip=info.get("ip", ""), name=info.get("name", ""), link=kind,
340
+ where=detail.get("bss") or detail.get("port") or "",
341
+ rssi=detail.get("rssi"), down_mbps=detail.get("down_speed"),
342
+ up_mbps=detail.get("up_speed"), down_bytes=detail.get("down_bytes"),
343
+ up_bytes=detail.get("up_bytes"), addressing=info.get("type", ""))
344
+ lease = leases.pop(mac, None)
345
+ if lease:
346
+ st.lease_remaining = lease.remaining
347
+ st.name = st.name or lease.name
348
+ st.reserved = mac in reserved
349
+ out.append(st)
350
+ return out
351
+
352
+ def wifi(self, secrets: bool = False) -> list:
353
+ """One row per SSID, with band and running state."""
354
+ bands = {b["band"]: b for b in self.call("wireless/band/show") or []}
355
+ band_info = {b["band"]: b for b in self.call("wireless/band/info") or []}
356
+ running = {b["bss"]: b for b in self.call("wireless/bss/info") or []}
357
+ counts: dict = {}
358
+ for st in self.stations():
359
+ if st.link == "wireless":
360
+ counts[st.where] = counts.get(st.where, 0) + 1
361
+ rows = []
362
+ for bss in self.call("wireless/bss/show") or []:
363
+ band = bss["bss"].split(".")[0]
364
+ row = {"bss": bss["bss"], "band": band, "ssid": bss.get("ssid", ""),
365
+ "enabled": bss.get("enable"), "running": (running.get(bss["bss"]) or {}).get("run"),
366
+ "hidden": bss.get("hide"), "security": bss.get("authenc", ""),
367
+ "channel": (band_info.get(band) or {}).get("channel") or (bands.get(band) or {}).get("channel"),
368
+ "width": (bands.get(band) or {}).get("width"),
369
+ "mode": (bands.get(band) or {}).get("mode"),
370
+ "clients": counts.get(bss["bss"], 0)}
371
+ if secrets:
372
+ row["password"] = bss.get("password", "")
373
+ rows.append(row)
374
+ return rows
375
+
376
+ def port_forwards(self, kind: str = "user") -> list:
377
+ out = []
378
+ for x in self.call("portforward/get", kind) or []:
379
+ out.append(PortForward(x["name"], x.get("protocol", ""), x.get("target", ""),
380
+ x.get("src", {}), x.get("dst", {}), bool(x.get("active", True)),
381
+ bool(x.get("fixed", False))))
382
+ return out
383
+
384
+ def remote_admin(self) -> dict:
385
+ return self.call("http/config")
386
+
387
+ # -- writes (never called unless you call them; honour dry_run) ----------------------------
388
+ def add_port_forward(self, name: str, target: str, protocol: str, external: str,
389
+ internal: Optional[str] = None, active: bool = True):
390
+ if protocol not in ("tcp", "udp", "tcpudp"):
391
+ raise IptimeError("protocol must be tcp, udp or tcpudp")
392
+ params = {"name": name, "active": active, "protocol": protocol, "target": target,
393
+ "src": parse_ports(external), "dst": parse_ports(internal or external)}
394
+ return self.call("portforward/add", params)
395
+
396
+ def del_port_forward(self, names: list, kind: str = "user"):
397
+ return self.call("portforward/del", {"type": kind, "list": list(names)})
398
+
399
+ def reserve(self, mac: str, ip: str, name: str = ""):
400
+ return self.call("dhcpd/reservedaddr/add",
401
+ {"ntag": "lan", "mac": normalize_mac(mac), "ip": ip, "desc": name})
402
+
403
+ def unreserve(self, mac: str):
404
+ return self.call("dhcpd/reservedaddr/del", {"ntag": "lan", "mac": [normalize_mac(mac)]})
405
+
406
+ def set_remote_admin(self, enabled: bool, port: Optional[int] = None):
407
+ """Turn remote (WAN) HTTP admin on or off. ``on`` exposes the admin page to the internet."""
408
+ current = self.remote_admin()
409
+ params = {"remotehttp_flag": bool(enabled),
410
+ "remotehttp_port": int(port or current.get("remotehttp_port") or 8080),
411
+ "commit": True}
412
+ return self.call("http/config", params)
413
+
414
+ def upgrade_firmware(self, wait_timeout: float = 1800, poll: float = 10, progress=None,
415
+ sleep=time.sleep, clock=time.monotonic) -> dict:
416
+ """Run the router's own online firmware upgrade and wait until it is back on the new version.
417
+
418
+ Sends ``firmware/upgrade/prepare {"method": "auto"}`` then ``firmware/upgrade/online`` (the
419
+ two calls the admin page's "upgrade now" makes), polls ``firmware/upgrade/status``, rides
420
+ out the reboot (the router is unreachable for a few minutes), logs in again and compares
421
+ ``firmware/info``. Nothing is uploaded; the router downloads the image itself.
422
+ ``progress(message)`` is called on each stage change. ``dry_run`` returns the two requests.
423
+ """
424
+ say = progress or (lambda _msg: None)
425
+ before = self.firmware()
426
+ old, latest = str(before.get("version")), before.get("latest")
427
+ if not before["update_available"]:
428
+ return {"upgraded": False, "reason": "already up to date", "from": old, "latest": latest}
429
+ if self.dry_run:
430
+ sent = [self.call_raw(m, p)["would_send"] for m, p in _UPGRADE_CALLS]
431
+ return {"dry_run": True, "upgraded": False, "from": old, "latest": latest, "would_send": sent}
432
+ started = clock()
433
+ for method, params in _UPGRADE_CALLS:
434
+ self.call(method, params)
435
+ say(f"upgrade requested: {old} -> {latest}")
436
+ active_seen, last_stage = False, None
437
+ while True:
438
+ if clock() - started > wait_timeout:
439
+ raise UpgradeError(f"gave up after {int(wait_timeout)}s waiting for the router "
440
+ f"(still on {old}?); it may still be rebooting")
441
+ status = None
442
+ try:
443
+ status = self.call("firmware/upgrade/status")
444
+ except IptimeError: # router rebooting: no answer, or the session is gone
445
+ self.logged_in = False
446
+ if last_stage != "unreachable":
447
+ say("router is rebooting (unreachable)")
448
+ last_stage, active_seen = "unreachable", True
449
+ if status:
450
+ stage = status.get("stage")
451
+ if stage == "failed":
452
+ raise UpgradeError(f"the router reports the upgrade failed: {status.get('failed') or 'unknown reason'}")
453
+ if stage != last_stage:
454
+ say(f"stage: {stage}")
455
+ last_stage = stage
456
+ if stage not in ("idle", None):
457
+ active_seen = True
458
+ if stage in ("idle", "succeeded") and active_seen:
459
+ try:
460
+ now = str(self.call("firmware/info").get("version"))
461
+ except IptimeError:
462
+ now = old
463
+ if now != old:
464
+ return {"upgraded": True, "from": old, "to": now, "latest": latest,
465
+ "seconds": int(clock() - started)}
466
+ elif stage == "idle" and clock() - started > 180:
467
+ raise UpgradeError("the router never started the upgrade (stage stayed idle)")
468
+ sleep(poll)
469
+
470
+ def reboot(self):
471
+ """Reboot the router now. The connection drops for a minute or two."""
472
+ return self.call("reboot/now")
473
+
474
+
475
+ _UPGRADE_CALLS = (("firmware/upgrade/prepare", {"method": "auto"}), ("firmware/upgrade/online", None))
476
+
477
+
478
+ def _version_key(text: str) -> tuple:
479
+ return tuple(int(p) if p.isdigit() else 0 for p in re.split(r"[.\-]", text))
480
+
481
+
482
+ def _try(router: Router, method: str, params: Any = None):
483
+ try:
484
+ return router.call(method, params)
485
+ except ApiError:
486
+ return None
487
+
488
+
489
+ def _mask(value: Any) -> Any:
490
+ """Replace every ``password`` value with ``********`` (the router returns Wi-Fi keys in clear)."""
491
+ if isinstance(value, dict):
492
+ return {k: ("********" if k == "password" and v else _mask(v)) for k, v in value.items()}
493
+ if isinstance(value, list):
494
+ return [_mask(v) for v in value]
495
+ return value
iptime_cli/config.py ADDED
@@ -0,0 +1,85 @@
1
+ """Settings: flags > environment > config file > defaults."""
2
+ from __future__ import annotations
3
+
4
+ import os
5
+ import stat
6
+ import sys
7
+ from dataclasses import dataclass
8
+
9
+ DEFAULT_HOST = "192.168.0.1" # ipTIME factory default
10
+ DEFAULT_USER = "admin"
11
+
12
+ _KEYS = {
13
+ "host": ("host", "url", "iptime_host", "iptime_admin_url"),
14
+ "user": ("user", "username", "iptime_user", "iptime_admin_user"),
15
+ "password": ("password", "pass", "iptime_password", "iptime_admin_password"),
16
+ }
17
+ _ENV = {
18
+ "host": ("IPTIME_HOST", "IPTIME_ADMIN_URL"),
19
+ "user": ("IPTIME_USER", "IPTIME_ADMIN_USER"),
20
+ "password": ("IPTIME_PASSWORD", "IPTIME_ADMIN_PASSWORD"),
21
+ }
22
+
23
+
24
+ @dataclass
25
+ class Settings:
26
+ host: str
27
+ user: str
28
+ password: str
29
+ config_path: str = ""
30
+
31
+
32
+ def default_config_path() -> str:
33
+ base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
34
+ return os.path.join(base, "iptime-cli", "config")
35
+
36
+
37
+ def read_file(path: str, warn=True) -> dict:
38
+ """Parse ``key = value`` lines (also ``IPTIME_HOST=...`` and ``export`` forms)."""
39
+ out: dict = {}
40
+ with open(path, encoding="utf-8") as fh:
41
+ for line in fh:
42
+ line = line.strip()
43
+ if not line or line.startswith("#") or ("=" not in line and ":" not in line):
44
+ continue
45
+ if line.startswith("export "):
46
+ line = line[7:]
47
+ key, _, value = line.partition("=") if "=" in line else line.partition(":")
48
+ key, value = key.strip().lower(), value.strip().strip("'\"")
49
+ for name, aliases in _KEYS.items():
50
+ if key in aliases:
51
+ out[name] = value
52
+ if warn and out.get("password"):
53
+ mode = stat.S_IMODE(os.stat(path).st_mode)
54
+ if mode & 0o077:
55
+ print(f"warning: {path} holds a password but is readable by others "
56
+ f"(mode {mode:04o}); run: chmod 600 {path}", file=sys.stderr)
57
+ return out
58
+
59
+
60
+ def resolve(host=None, user=None, config=None, prompt=True) -> Settings:
61
+ path = config or os.environ.get("IPTIME_CONFIG") or default_config_path()
62
+ values: dict = {}
63
+ if os.path.exists(path):
64
+ values = read_file(path)
65
+ elif config:
66
+ raise SystemExit(f"config file not found: {config}")
67
+
68
+ def pick(name, flag):
69
+ if flag:
70
+ return flag
71
+ for var in _ENV[name]:
72
+ if os.environ.get(var):
73
+ return os.environ[var]
74
+ return values.get(name, "")
75
+
76
+ settings = Settings(pick("host", host) or DEFAULT_HOST, pick("user", user) or DEFAULT_USER,
77
+ pick("password", None), path if values else "")
78
+ if not settings.password and prompt:
79
+ if sys.stdin.isatty():
80
+ import getpass
81
+ settings.password = getpass.getpass(f"password for {settings.user}@{settings.host}: ")
82
+ else:
83
+ raise SystemExit("error: no password. Set IPTIME_PASSWORD, put it in "
84
+ f"{default_config_path()}, or run in a terminal to be asked.")
85
+ return settings