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/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ """Unofficial CLI and library for ipTIME routers with the new admin UI (firmware 16.x)."""
2
+ from .client import (ApiError, CaptchaError, ConnectError, IptimeError, Lease, LockoutError,
3
+ LoginError, OldUiError, PortForward, Reservation, Router, Station, UpgradeError)
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["Router", "Station", "Lease", "Reservation", "PortForward", "IptimeError", "ApiError",
7
+ "LoginError", "CaptchaError", "LockoutError", "OldUiError", "ConnectError", "UpgradeError"]
iptime_cli/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
iptime_cli/catalog.py ADDED
@@ -0,0 +1,219 @@
1
+ """Catalog of JSON-API methods the ipTIME admin UI (Flutter, firmware 16.x) calls.
2
+
3
+ Every request is ``POST /cgi/service.cgi {"method": ..., "params": ...}``. The list below was
4
+ extracted from the admin bundle the router serves (``/ui/main.dart.js``, build 16.00.0). A
5
+ method is only marked ``ok`` when it was actually called against a real router and answered.
6
+
7
+ status values:
8
+ ok called on real hardware (read-only), answered
9
+ absent called on real hardware, the model answered "Method not found" or "Config error"
10
+ used write method that an earlier hand-written script sent to real hardware. This package's
11
+ own write code has only been exercised against the bundled fake router.
12
+ bundle present in the admin bundle, never called by us
13
+ """
14
+ from __future__ import annotations
15
+
16
+ FIRMWARE = "16.00.0"
17
+
18
+ # last path segments that only read
19
+ _READ_SEGMENTS = {
20
+ "get", "show", "info", "status", "list", "max", "stations", "stalist", "chart", "spec", "state",
21
+ "count", "supported_fs", "support", "support_func", "name", "num", "role", "running", "latest",
22
+ "is_set", "has", "read", "progressing", "params", "pcount", "storage", "temperature", "auth",
23
+ "account", "profile", "services", "original", "all", "agent", "online", "user_count", "changed",
24
+ "backup", "expire", "port", "portcfg", "relay", "rssi", "min", "range",
25
+ }
26
+ # last segments that change state or trigger an action
27
+ _WRITE_SEGMENTS = {
28
+ "add", "set", "del", "remove", "clear", "start", "stop", "update", "new", "enroll", "cancel",
29
+ "connect", "disconnect", "reset", "restore", "gen", "flush", "suspend", "resume", "apply",
30
+ "upgrade", "prepare", "now", "timer", "beep", "convert", "scrub", "mount", "umount", "download",
31
+ "send", "scan", "signal", "operation", "enable", "modify", "delall", "online_upgrade", "ctrl",
32
+ "report_on_error", "redirect_on_error", "mode", "policy", "delete", "change",
33
+ }
34
+ # explicitly dangerous: loses config, drops the connection or flashes firmware
35
+ DANGER = {
36
+ "reboot/now", "reboot/timer", "config/reset", "config/restore", "default/admin",
37
+ "firmware/upgrade/online", "firmware/upgrade/prepare", "network/interface/wan1/suspend",
38
+ "network/interface/wan1/resume", "network/arp/flush", "partition/add", "partition/del",
39
+ "btrfs/subvol/convert", "usb/umount", "https/cert/del", "https/cert/gen", "admin/account",
40
+ "wireless/band/set",
41
+ }
42
+ # "<name>/config" style methods read without params and write with params
43
+ _CONFIG_LIKE = ("config", "config/get", "get")
44
+
45
+ SESSION = {"session/login", "session/logout", "session/update", "session/info"}
46
+
47
+
48
+ def classify(method: str, params=None) -> str:
49
+ """Return ``read``, ``write``, ``danger`` or ``session``.
50
+
51
+ Unknown names that do not look like a read are reported as ``write`` so that guards stay on
52
+ the safe side.
53
+ """
54
+ if method in SESSION:
55
+ return "session"
56
+ if method in DANGER:
57
+ return "danger"
58
+ last = method.rsplit("/", 1)[-1]
59
+ if last == "config" or method.endswith("/config/original"):
60
+ return "read" if params is None else "write"
61
+ if last in _WRITE_SEGMENTS:
62
+ return "write"
63
+ if last in _READ_SEGMENTS:
64
+ return "read"
65
+ return "write"
66
+
67
+
68
+ # method | params | note | status
69
+ _OBSERVED = """
70
+ session/info||who am I: ip, mac, location, idle timeout, level|ok
71
+ admin/auth/info||login policy: auth mode, session timeout, captcha use/tolerance|ok
72
+ product/info||model, id, board, MACs, vendor, mesh support|ok
73
+ product/name||model name string|ok
74
+ system/info||version, uptime, WAN link speed, DHCP range, SSIDs (incl. Wi-Fi passwords in clear)|ok
75
+ system/name||device name|ok
76
+ system/temperature|"cpu"|CPU temperature; this model answers "Config error"|absent
77
+ firmware/info||running firmware: version, build date, snapshot id|ok
78
+ firmware/version/latest||newest firmware version the router knows of|ok
79
+ firmware/upgrade/status||stage idle, starting, checking, downloading, waiting, writing, succeeded or failed (plus a downloading percent and a failed reason: download, format, version, internal)|ok
80
+ network/interface/wan1/info||WAN type, link, status, IP, mask, gateway, MAC, MTU, connected seconds|ok
81
+ network/interface/wan1/config||WAN configuration (type, DHCP/PPPoE/static options)|ok
82
+ network/interface/lan/info||LAN bridge: IP, mask, MAC, MTU|ok
83
+ network/interface/lan/config||LAN configuration|ok
84
+ network/interface/lan/stations||every device the router sees: MAC, IP, name, wired port or Wi-Fi BSS/RSSI/speeds|ok
85
+ network/dns/info||DNS servers in use|ok
86
+ network/dns/config||manual DNS settings|ok
87
+ conn/info||connection-tracking totals per LAN host|ok
88
+ dhcpd/status|"lan"|DHCP server running or suspended|ok
89
+ dhcpd/config/get|"lan"|DHCP pool, mask, gateway, DNS, lease time|ok
90
+ dhcpd/lease/show|"lan"|current leases: MAC, IP, remaining seconds, hostname|ok
91
+ dhcpd/reservedaddr/show|"lan"|static DHCP reservations|ok
92
+ wireless/info||per band: supported modes, widths, authentication, country|ok
93
+ wireless/band/info||per band: activated, channel, bandwidth, DFS state|ok
94
+ wireless/band/show||per band settings: channel, mode, width, TX power, streams|ok
95
+ wireless/bss/info||per SSID: running, MAC, interface|ok
96
+ wireless/bss/show||per SSID settings: SSID, hidden, authentication, password (in clear), max stations|ok
97
+ wireless/client/info||repeater/client-mode link state per band|ok
98
+ wireless/client/show||repeater/client-mode settings per band|ok
99
+ wireless/mac/show||Wi-Fi MAC filter policy and list per SSID|ok
100
+ wireless/wps/info||WPS state per band|ok
101
+ wireless/mlo/info||Wi-Fi 7 multi-link operation; this model answers "Method not found"|absent
102
+ port/num||{"wan": 1, "lan": 4}|ok
103
+ port/link/info||per port: supported speeds|ok
104
+ port/link/status||per port: negotiated link speed|ok
105
+ port/stat/get||per port rx/tx packet and byte counters|ok
106
+ port/role||switch port role; this model answers "Method not found"|absent
107
+ power/status||this model answers "Method not found"|absent
108
+ fan/running||this model answers "Method not found"|absent
109
+ led/status||LED on or off|ok
110
+ tethering/status||USB tethering state|ok
111
+ upnp/config||UPnP enabled flag|ok
112
+ nat/config||NAT enabled flag|ok
113
+ dmz/config||DMZ mode, host MAC, lease|ok
114
+ http/config|none to read; {"remotehttp_flag","remotehttp_port","commit":true} to write|admin ports and remote (WAN) admin flags; the write body is from the admin bundle, never sent by us|ok
115
+ time/config||time server, time zone, DST|ok
116
+ portforward/get|"user" or "upnp"|port-forward rules: name, active, protocol, target, src (external) and dst (internal) ports|ok
117
+ portforward/max||maximum number of rules|ok
118
+ wol/show||Wake-on-LAN list|ok
119
+ route/static/show||static routes|ok
120
+ qos/rule/show||QoS rules|ok
121
+ firewall/get||firewall rules|ok
122
+ easymesh/info||EasyMesh active flag and role|ok
123
+ usb/show||USB devices and partitions|ok
124
+ wan/heartbeat||WAN heartbeat (keep-alive) settings|ok
125
+ ui/lang/config||admin UI language|ok
126
+ session/login|{"id","pw"}|log in; answers {"result": "done"}; sets the session cookie|used
127
+ session/logout||log out|ok
128
+ portforward/add|{"name","active","protocol","target","src":{"start"[,"end"]},"dst":{...}}|add a rule|used
129
+ portforward/set||change a rule|used
130
+ portforward/del|{"type":"user","list":[names]}|delete rules by name; answers the new list|used
131
+ dhcpd/reservedaddr/add|{"ntag":"lan","mac","ip","desc"}|one reservation per call|used
132
+ dhcpd/reservedaddr/del|{"ntag":"lan","mac":[macs]}|delete reservations|used
133
+ firmware/upgrade/prepare|{"method":"auto"}|step 1 of "upgrade now" (online upgrade); never sent to real hardware by us|bundle
134
+ firmware/upgrade/online||step 2: the router downloads and flashes the latest image itself, then reboots; an error answer means nothing to upgrade; never sent to real hardware by us|bundle
135
+ reboot/now||reboot the router immediately; never called by us|bundle
136
+ """
137
+
138
+
139
+ def _parse():
140
+ out = {}
141
+ for line in _OBSERVED.strip().splitlines():
142
+ name, params, note, status = line.split("|")
143
+ out[name] = {"params": params, "note": note, "status": status}
144
+ return out
145
+
146
+
147
+ OBSERVED = _parse()
148
+
149
+ _BUNDLE_NAMES = """
150
+ acl/config acl/whitelist/add acl/whitelist/del admin/account admin/auth admin/auth/info
151
+ admin/changed admin/email admin/email/clear admin/email/is_set api/has assistance/config
152
+ assistance/icc/config assistance/icc/info btrfs/scrub btrfs/subvol/convert captcha/new
153
+ cert/remote config/backup config/reset config/restore conn/ctrl conn/defaults conn/info
154
+ cupsd/config cupsd/status cwmp/get cwmp/set cwmp/status ddns/config ddns/config/add
155
+ ddns/config/del ddns/status/clear ddns/status/get ddns/update default/admin dhcpd/config/get
156
+ dhcpd/config/set dhcpd/lease/show dhcpd/reservedaddr/add dhcpd/reservedaddr/del
157
+ dhcpd/reservedaddr/show dhcpd/status diffserv/config dmz/config dos/config easymesh/config
158
+ easymesh/info easymesh/show/agent fan/config fan/config/original fan/running firewall/add
159
+ firewall/del firewall/get firewall/max firewall/set firmware/info firmware/upgrade/online
160
+ firmware/upgrade/prepare firmware/upgrade/status firmware/version/latest fm/guest/account
161
+ fm/guest/account/delete fm/guest/online fm/list ftp/config ftp/port/add ftp/port/del
162
+ ftp/port/list geoip/blocked/pcount geoip/country/list geoip/db/download geoip/enable geoip/get
163
+ geoip/policy/remove geoip/policy/set geoip/white/list geoip/white/remove geoip/white/set
164
+ history/range/spec history/station/connection/state
165
+ history/station/count/chart history/station/count/max history/station/count/stalist
166
+ history/station/disconnection/count/chart history/station/disconnection/count/max
167
+ history/station/rssi/chart history/station/rssi/min historyd/clear historyd/config
168
+ historyd/storage hostscan/log/clear hostscan/log/read hostscan/params hostscan/progressing
169
+ hostscan/start hostscan/stop http/config httpd/direct/portcfg https/cert/config https/cert/del
170
+ https/cert/gen https/cert/get https/cert/info https/cert/set httpsd/port icc/cli/connect/status
171
+ icc/cli/enroll icc/cli/enroll/cancel icc/cli/enroll/info icc/cli/enroll/status icc/cli/profile
172
+ icc/cli/site_config/show id/device/user_count id/keyset/list id/keyset/remove_user iptv/config
173
+ iptv/mode iptv/public/port l2tp/server/config led/config led/status macvlan/add macvlan/del
174
+ macvlan/get media/config media/db/show media/db/update mudfish/config mudfish/status
175
+ nas/user/add nas/user/del nas/user/info nas/user/modify nas/user/show nas/user/show/online
176
+ nat/config network/arp/flush network/dns/config network/dns/info network/info
177
+ network/interface/lan/config network/interface/lan/info network/interface/lan/scan/apcp
178
+ network/interface/lan/scan/dhcp network/interface/lan/stations network/interface/wan1/config
179
+ network/interface/wan1/info network/interface/wan1/resume network/interface/wan1/scan
180
+ network/interface/wan1/suspend partition/add partition/del partition/supported_fs
181
+ port/link/config port/link/info port/link/status port/num port/role port/stat/clear
182
+ port/stat/get portforward/add portforward/config portforward/del portforward/get
183
+ portforward/max portforward/set power/beep power/report_on_error power/status ppp/user/add
184
+ ppp/user/del ppp/user/disconnect ppp/user/max ppp/user/set ppp/user/show pptp/server/config
185
+ product/info product/name product/support_func qos/config qos/rule/del qos/rule/set
186
+ qos/rule/show reboot/now reboot/timer route/static/add route/static/del route/static/max
187
+ route/static/set route/static/show routine/add routine/del routine/expire routine/get
188
+ routine/services routine/set routine/status samba/config session/info session/login
189
+ session/logout session/update si/net/profile si/net/profile/clear snapshot/config
190
+ snapshot/delall snapshot/new switch/jumbo_frame/config switch/mirror/config switch/mirror/port
191
+ switch/trunk/config switch/trunk/port syslog/active syslog/clear syslog/email/config
192
+ syslog/email/send syslog/max syslog/show system/info system/name system/temperature
193
+ tethering/config tethering/status time/config torrent/config ui/lang/config ui/lang/list
194
+ ui/redirect_on_error upnp/config upnp/relay url/config urlredir/config urlredir/freedevice/add
195
+ urlredir/freedevice/del urlredir/freedevice/show usb/event/count usb/mode usb/mount
196
+ usb/mount/list usb/service/apply usb/service/status usb/show usb/umount vpncli/connect
197
+ vpncli/disconnect vpncli/filter/list vpncli/filter/remove vpncli/filter/set vpncli/server/list
198
+ vpncli/server/remove vpncli/server/set vpncli/status/list vpncli/upload/config wan/heartbeat
199
+ wg/client/add wg/client/change wg/client/del wg/client/show wg/peer/add wg/peer/change
200
+ wg/peer/del wg/peer/show wg/server/clear wg/server/set wg/server/show wireless/band/info
201
+ wireless/band/set wireless/band/show wireless/band/support wireless/bss/clear wireless/bss/info
202
+ wireless/bss/set wireless/bss/show wireless/channel/list wireless/channel/scan
203
+ wireless/client/info wireless/client/set wireless/client/show wireless/info wireless/mac/add
204
+ wireless/mac/del wireless/mac/policy wireless/mac/show wireless/mlo/info wireless/scan
205
+ wireless/wps/info wireless/wps/start wireless/wps/stop wl/operation wol/add wol/del wol/show
206
+ wol/signal
207
+ """.split()
208
+
209
+
210
+ def all_methods():
211
+ """Return ``[{method, kind, status, firmware, params, note}]`` sorted by name."""
212
+ rows = []
213
+ for name in sorted(set(_BUNDLE_NAMES) | set(OBSERVED)):
214
+ info = OBSERVED.get(name, {"params": "", "note": "", "status": "bundle"})
215
+ rows.append({
216
+ "method": name, "kind": classify(name), "status": info["status"],
217
+ "firmware": FIRMWARE, "params": info["params"], "note": info["note"],
218
+ })
219
+ return rows
iptime_cli/cli.py ADDED
@@ -0,0 +1,385 @@
1
+ """``iptime`` command line."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ import time
8
+
9
+ from . import __version__, config
10
+ from .catalog import all_methods, classify
11
+ from .client import IptimeError, PortForward, Router, normalize_mac
12
+ from .render import human_bytes, human_duration, pairs, table
13
+
14
+ EPILOG = """\
15
+ Write commands (port add/rm, dhcp reserve/unreserve, remote-admin on|off, reboot) change the router.
16
+ Add --dry-run to print the request instead of sending it. Logging in may end an admin session that
17
+ is open in a browser. Unofficial; not affiliated with EFM Networks."""
18
+
19
+
20
+ def build_parser() -> argparse.ArgumentParser:
21
+ def make_common(sub: bool) -> argparse.ArgumentParser:
22
+ """Connection/output flags; accepted before and after the command."""
23
+ S = argparse.SUPPRESS
24
+
25
+ def d(value):
26
+ return S if sub else value
27
+
28
+ c = argparse.ArgumentParser(add_help=False)
29
+ g = c.add_argument_group("connection")
30
+ g.add_argument("--host", default=d(None), help="router address (default: IPTIME_HOST or 192.168.0.1)")
31
+ g.add_argument("--user", default=d(None), help="admin user (default: IPTIME_USER or admin)")
32
+ g.add_argument("--config", metavar="FILE", default=d(None), help="config file (default ~/.config/iptime-cli/config)")
33
+ g.add_argument("--timeout", type=float, default=d(15), help="seconds per request (default 15)")
34
+ g.add_argument("--insecure", action="store_true", default=d(False), help="do not verify a self-signed https certificate")
35
+ o = c.add_argument_group("output")
36
+ o.add_argument("--json", action="store_true", default=d(False), help="print JSON instead of a table")
37
+ o.add_argument("--show-secrets", action="store_true", default=d(False), help="show Wi-Fi passwords (hidden by default)")
38
+ w = c.add_argument_group("writes")
39
+ w.add_argument("--dry-run", action="store_true", default=d(False), help="print the request instead of sending a write")
40
+ w.add_argument("-y", "--yes", action="store_true", default=d(False), help="do not ask before a write")
41
+ return c
42
+
43
+ common = make_common(True)
44
+
45
+ p = argparse.ArgumentParser(prog="iptime", description="Unofficial command line for ipTIME routers with the new admin UI (firmware 16.x).",
46
+ epilog=EPILOG, formatter_class=argparse.RawDescriptionHelpFormatter)
47
+ p.add_argument("--version", action="version", version=f"iptime-cli {__version__}")
48
+ for action in make_common(False)._actions:
49
+ if action.dest != "help":
50
+ p._add_action(action)
51
+ sub = p.add_subparsers(dest="command", required=True, metavar="COMMAND")
52
+
53
+ def add(name, help, **kw):
54
+ return sub.add_parser(name, help=help, parents=[common], description=help, **kw)
55
+
56
+ add("info", "model, firmware (and whether a newer one exists), uptime, LAN/WAN summary")
57
+ c = add("clients", "every device the router sees: wired and Wi-Fi, with DHCP lease info")
58
+ c.add_argument("--wireless", action="store_true", help="only Wi-Fi devices")
59
+ c.add_argument("--wired", action="store_true", help="only wired devices")
60
+ add("wan", "WAN link: type, IP, gateway, DNS, link speed, traffic")
61
+ add("wifi", "SSIDs, bands, channels and security")
62
+
63
+ pt = add("port", "port forwarding rules")
64
+ ps = pt.add_subparsers(dest="action", required=True, metavar="ACTION")
65
+
66
+ def padd(name, help):
67
+ return ps.add_parser(name, help=help, parents=[common], description=help)
68
+
69
+ pl = padd("list", "list rules")
70
+ pl.add_argument("--upnp", action="store_true", help="show rules added by UPnP instead")
71
+ pa = padd("add", "add a rule")
72
+ pa.add_argument("name")
73
+ pa.add_argument("--target", required=True, metavar="IP", help="LAN address to forward to")
74
+ pa.add_argument("--proto", default="tcp", choices=["tcp", "udp", "tcpudp"])
75
+ pa.add_argument("--ext", required=True, metavar="PORT[-END]", help="external (WAN) port or range")
76
+ pa.add_argument("--int", dest="internal", metavar="PORT[-END]", help="internal port or range (default: same as --ext)")
77
+ pa.add_argument("--disabled", action="store_true", help="add the rule switched off")
78
+ pr = padd("rm", "remove rules by name")
79
+ pr.add_argument("names", nargs="+")
80
+
81
+ dh = add("dhcp", "DHCP leases and static reservations")
82
+ ds = dh.add_subparsers(dest="action", required=True, metavar="ACTION")
83
+
84
+ def dadd(name, help):
85
+ return ds.add_parser(name, help=help, parents=[common], description=help)
86
+
87
+ dadd("list", "leases and reservations")
88
+ dr = dadd("reserve", "reserve an address for a MAC")
89
+ dr.add_argument("mac")
90
+ dr.add_argument("ip")
91
+ dr.add_argument("--name", default="iptime-cli", help="description shown in the admin UI")
92
+ du = dadd("unreserve", "remove the reservation of a MAC")
93
+ du.add_argument("mac")
94
+
95
+ ra = add("remote-admin", "show, or switch, admin access from the internet (WAN)")
96
+ ra.add_argument("state", nargs="?", choices=["on", "off"], help="omit to just show the state")
97
+ ra.add_argument("--port", type=int, help="WAN admin port when switching on (default: the stored one)")
98
+
99
+ fw = add("firmware", "check for, or install, a newer firmware (the router's own online upgrade)")
100
+ fs = fw.add_subparsers(dest="action", required=True, metavar="ACTION")
101
+
102
+ def fadd(name, help):
103
+ return fs.add_parser(name, help=help, parents=[common], description=help)
104
+
105
+ fadd("check", "running firmware vs the newest one the router knows of")
106
+ fu = fadd("upgrade", "install the newest firmware; the router reboots and the network drops for a few minutes")
107
+ fu.add_argument("--if-available", action="store_true", help="do nothing, quietly, when already up to date")
108
+ fu.add_argument("--wait-timeout", type=float, default=1800, metavar="SECONDS",
109
+ help="how long to wait for the router to come back on the new version (default 1800)")
110
+ fu.add_argument("--poll", type=float, default=10, metavar="SECONDS", help="status poll interval (default 10)")
111
+
112
+ add("reboot", "reboot the router now (asks first; connection drops for a minute or two)")
113
+
114
+ ca = add("call", "send one raw API call (escape hatch)")
115
+ ca.add_argument("method")
116
+ ca.add_argument("params", nargs="?", help='JSON, e.g. \'"user"\' or \'{"ntag":"lan"}\'')
117
+ ca.add_argument("--write", action="store_true", help="allow a method that is not a read")
118
+
119
+ m = sub.add_parser("methods", help="list the API methods found in the admin UI", parents=[common],
120
+ description="List the API methods found in the admin UI bundle (no router needed).")
121
+ m.add_argument("--kind", choices=["read", "write", "danger", "session"])
122
+ m.add_argument("--seen", action="store_true", help="only methods called on real hardware")
123
+ return p
124
+
125
+
126
+ def emit(args, data, text: str) -> None:
127
+ print(json.dumps(data, ensure_ascii=False, indent=2) if args.json else text)
128
+
129
+
130
+ def confirm(args, what: str) -> bool:
131
+ if args.dry_run or args.yes:
132
+ return True
133
+ if not sys.stdin.isatty():
134
+ raise IptimeError(f"refusing to {what} without --yes (no terminal to ask on); "
135
+ "use --dry-run to see the request")
136
+ try:
137
+ return input(f"{what}? [y/N] ").strip().lower() in ("y", "yes")
138
+ except EOFError:
139
+ return False
140
+
141
+
142
+ def rules_table(rules: list) -> str:
143
+ return table(["NAME", "PROTO", "EXTERNAL", "TARGET", "INTERNAL", "ON"],
144
+ [[x["name"], x.get("protocol"), PortForward.span(x.get("src", {})), x.get("target"),
145
+ PortForward.span(x.get("dst", {})), "yes" if x.get("active") else "no"] for x in rules])
146
+
147
+
148
+ def show_write(args, result) -> None:
149
+ if isinstance(result, list) and not args.json and all(isinstance(x, dict) and "src" in x for x in result):
150
+ print("ok, rules now:\n" + rules_table(result))
151
+ elif isinstance(result, dict) and result.get("dry_run"):
152
+ sent = result["would_send"]
153
+ emit(args, result, f"dry run, nothing sent:\nPOST {sent['POST']}\n"
154
+ f"{json.dumps(sent['body'], ensure_ascii=False)}")
155
+ else:
156
+ emit(args, {"ok": True, "result": result}, f"ok: {json.dumps(result, ensure_ascii=False)}")
157
+
158
+
159
+ def _ipkey(ip: str) -> tuple:
160
+ return tuple(int(p) if p.isdigit() else 0 for p in ip.split("."))
161
+
162
+
163
+ def cmd_info(args, r: Router):
164
+ prod, fw, sys_ = r.product(), r.firmware(), r.system()
165
+ lan, wan = r.lan(), r.wan()
166
+ data = {"product": prod, "firmware": fw, "system": {k: v for k, v in sys_.items() if k != "wireless"},
167
+ "lan": lan, "wan": wan}
168
+ latest = fw.get("latest")
169
+ note = f"{latest} (update available)" if fw.get("update_available") else f"{latest} (up to date)" if latest else "unknown"
170
+ dhcp = lan.get("dhcp") or {}
171
+ emit(args, data, pairs([
172
+ ("Model", prod.get("name")),
173
+ ("Firmware", f"{fw.get('version')} (built {fw.get('build_date')})"),
174
+ ("Latest firmware", note),
175
+ ("Uptime", human_duration(sys_.get("uptime"))),
176
+ ("LAN", f"{lan.get('ip')} / {lan.get('mask')}"),
177
+ ("DHCP pool", f"{dhcp.get('min_ip')} - {dhcp.get('max_ip')}" if dhcp else ""),
178
+ ("WAN", f"{wan.get('type')} {wan.get('ip')} gateway {wan.get('gateway')} {wan.get('status')}"),
179
+ ("WAN link", wan.get("link_speed")),
180
+ ]))
181
+
182
+
183
+ def cmd_clients(args, r: Router):
184
+ rows = r.stations()
185
+ if args.wireless:
186
+ rows = [x for x in rows if x.link == "wireless"]
187
+ if args.wired:
188
+ rows = [x for x in rows if x.link == "wired"]
189
+ rows.sort(key=lambda x: _ipkey(x.ip))
190
+ if args.json:
191
+ print(json.dumps([x.as_dict() for x in rows], ensure_ascii=False, indent=2))
192
+ return
193
+ body = []
194
+ for x in rows:
195
+ link = f"{x.where} {x.rssi} dBm" if x.link == "wireless" else f"{x.where} wired"
196
+ lease = human_duration(x.lease_remaining) if x.lease_remaining is not None else ("static" if x.addressing == "static" else "")
197
+ body.append([x.ip, x.mac, x.name, link, lease, "yes" if x.reserved else ""])
198
+ print(table(["IP", "MAC", "NAME", "LINK", "LEASE LEFT", "RESERVED"], body))
199
+
200
+
201
+ def cmd_wan(args, r: Router):
202
+ w = r.wan()
203
+ emit(args, w, pairs([
204
+ ("Type", w.get("type")), ("Status", f"{w.get('status')} ({w.get('protocol_status')})"),
205
+ ("IP", w.get("ip")), ("Mask", w.get("mask")), ("Gateway", w.get("gateway")),
206
+ ("DNS", ", ".join(w.get("dns") or [])), ("MAC", w.get("mac")), ("MTU", w.get("mtu")),
207
+ ("Link speed", w.get("link_speed")), ("Connected for", human_duration(w.get("connected_period"))),
208
+ ("Received", human_bytes(w.get("rx_bytes"))), ("Sent", human_bytes(w.get("tx_bytes"))),
209
+ ]))
210
+
211
+
212
+ def cmd_wifi(args, r: Router):
213
+ rows = r.wifi(secrets=args.show_secrets)
214
+ if args.json:
215
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
216
+ return
217
+ head = ["BSS", "SSID", "BAND", "CH", "SECURITY", "ON", "HIDDEN", "CLIENTS"]
218
+ if args.show_secrets:
219
+ head.append("PASSWORD")
220
+ body = []
221
+ for x in rows:
222
+ row = [x["bss"], x["ssid"], f"{x['band']} {x['mode']}/{x['width']}MHz", x["channel"], x["security"],
223
+ "yes" if x["running"] else "no", "yes" if x["hidden"] else "", x["clients"]]
224
+ if args.show_secrets:
225
+ row.append(x.get("password", ""))
226
+ body.append(row)
227
+ print(table(head, body))
228
+
229
+
230
+ def cmd_port(args, r: Router):
231
+ if args.action == "list":
232
+ rules = r.port_forwards("upnp" if args.upnp else "user")
233
+ if args.json:
234
+ print(json.dumps([x.as_dict() for x in rules], ensure_ascii=False, indent=2))
235
+ return
236
+ print(table(["NAME", "PROTO", "EXTERNAL", "TARGET", "INTERNAL", "ON"],
237
+ [[x.name, x.protocol, PortForward.span(x.external), x.target,
238
+ PortForward.span(x.internal), "yes" if x.active else "no"] for x in rules]))
239
+ elif args.action == "add":
240
+ if not confirm(args, f"add port forward {args.name!r} {args.ext} -> {args.target}"):
241
+ return
242
+ show_write(args, r.add_port_forward(args.name, args.target, args.proto, args.ext,
243
+ args.internal, not args.disabled))
244
+ elif args.action == "rm":
245
+ if not confirm(args, f"remove port forward {', '.join(args.names)}"):
246
+ return
247
+ show_write(args, r.del_port_forward(args.names))
248
+
249
+
250
+ def cmd_dhcp(args, r: Router):
251
+ if args.action == "list":
252
+ reserved = {x.mac: x for x in r.reservations()}
253
+ leases = {x.mac: x for x in r.leases()}
254
+ rows = []
255
+ for mac in sorted(set(reserved) | set(leases), key=lambda m: _ipkey((reserved.get(m) or leases[m]).ip)):
256
+ res, lease = reserved.get(mac), leases.get(mac)
257
+ state = "reserved+leased" if res and lease else "reserved" if res else "leased"
258
+ rows.append({"ip": (res or lease).ip, "mac": mac, "name": (res.name if res and res.name else lease.name if lease else ""),
259
+ "state": state, "lease_remaining": lease.remaining if lease else None})
260
+ if args.json:
261
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
262
+ return
263
+ print(table(["IP", "MAC", "NAME", "STATE", "LEASE LEFT"],
264
+ [[x["ip"], x["mac"], x["name"], x["state"],
265
+ human_duration(x["lease_remaining"]) if x["lease_remaining"] is not None else ""] for x in rows]))
266
+ elif args.action == "reserve":
267
+ if not confirm(args, f"reserve {args.ip} for {normalize_mac(args.mac)}"):
268
+ return
269
+ show_write(args, r.reserve(args.mac, args.ip, args.name))
270
+ elif args.action == "unreserve":
271
+ if not confirm(args, f"remove the reservation of {normalize_mac(args.mac)}"):
272
+ return
273
+ show_write(args, r.unreserve(args.mac))
274
+
275
+
276
+ def cmd_remote_admin(args, r: Router):
277
+ if args.state is None:
278
+ c = r.remote_admin()
279
+ emit(args, c, pairs([
280
+ ("LAN admin", f"{c.get('mode')} port {c.get('http_port')}"),
281
+ ("Remote HTTP", f"{'on' if c.get('remotehttp_flag') else 'off'}, port {c.get('remotehttp_port')}"),
282
+ ("Remote HTTPS", f"{'on' if c.get('remotehttps_flag') else 'off'}, port {c.get('remotehttps_port')}")]))
283
+ return
284
+ on = args.state == "on"
285
+ if on:
286
+ print("warning: this opens the router's admin page to the internet.", file=sys.stderr)
287
+ if not confirm(args, f"switch remote admin {args.state}"):
288
+ return
289
+ show_write(args, r.set_remote_admin(on, args.port))
290
+
291
+
292
+ def cmd_firmware(args, r: Router):
293
+ fw = r.firmware()
294
+ if args.action == "check":
295
+ latest = fw.get("latest")
296
+ state = "update available" if fw["update_available"] else "up to date" if latest else "unknown"
297
+ emit(args, fw, pairs([("Running", f"{fw.get('version')} (built {fw.get('build_date')})"),
298
+ ("Latest", latest), ("State", state)]))
299
+ return
300
+ if not fw["update_available"]:
301
+ if not args.if_available:
302
+ emit(args, {"upgraded": False, "from": fw.get("version"), "latest": fw.get("latest")},
303
+ f"firmware {fw.get('version')} is already the newest ({fw.get('latest')}); nothing to do")
304
+ return
305
+ if not confirm(args, f"upgrade firmware {fw.get('version')} -> {fw.get('latest')} "
306
+ "(the router reboots; the network drops for a few minutes)"):
307
+ return
308
+ log = (lambda m: print(f"[{time.strftime('%H:%M:%S')}] {m}", file=sys.stderr, flush=True))
309
+ res = r.upgrade_firmware(args.wait_timeout, args.poll, progress=None if args.json else log)
310
+ if res.get("dry_run"):
311
+ print(f"dry run, nothing sent ({res['from']} -> {res['latest']}):" if not args.json else "", end="")
312
+ if args.json:
313
+ print(json.dumps(res, ensure_ascii=False, indent=2))
314
+ else:
315
+ print()
316
+ for sent in res["would_send"]:
317
+ print(f"POST {sent['POST']}\n{json.dumps(sent['body'], ensure_ascii=False)}")
318
+ return
319
+ emit(args, res, f"firmware upgraded {res['from']} -> {res['to']} in {human_duration(res['seconds'])}")
320
+
321
+
322
+ def cmd_reboot(args, r: Router):
323
+ if not confirm(args, "reboot the router now"):
324
+ return
325
+ show_write(args, r.reboot())
326
+
327
+
328
+ def cmd_call(args, r: Router):
329
+ params = None
330
+ if args.params is not None:
331
+ try:
332
+ params = json.loads(args.params)
333
+ except json.JSONDecodeError:
334
+ params = args.params # a bare word such as: call portforward/get user
335
+ kind = classify(args.method, params)
336
+ if kind in ("write", "danger") and not (args.write or args.dry_run):
337
+ raise IptimeError(f"{args.method} is not a read ({kind}); add --write to send it, or --dry-run to see the request")
338
+ if kind in ("write", "danger") and not confirm(args, f"send {args.method}"):
339
+ return
340
+ resp = r.call_raw(args.method, params)
341
+ print(json.dumps(resp, ensure_ascii=False, indent=1))
342
+ if resp.get("error"):
343
+ raise SystemExit(1)
344
+
345
+
346
+ def cmd_methods(args):
347
+ rows = all_methods()
348
+ if args.kind:
349
+ rows = [x for x in rows if x["kind"] == args.kind]
350
+ if args.seen:
351
+ rows = [x for x in rows if x["status"] != "bundle"]
352
+ if args.json:
353
+ print(json.dumps(rows, ensure_ascii=False, indent=2))
354
+ return
355
+ print(table(["METHOD", "KIND", "STATUS", "FIRMWARE", "NOTE"],
356
+ [[x["method"], x["kind"], x["status"], x["firmware"], x["note"]] for x in rows]))
357
+
358
+
359
+ HANDLERS = {"info": cmd_info, "clients": cmd_clients, "wan": cmd_wan, "wifi": cmd_wifi, "port": cmd_port,
360
+ "dhcp": cmd_dhcp, "firmware": cmd_firmware, "remote-admin": cmd_remote_admin, "reboot": cmd_reboot, "call": cmd_call}
361
+
362
+
363
+ def main(argv=None) -> int:
364
+ args = build_parser().parse_args(argv)
365
+ try:
366
+ if args.command == "methods":
367
+ cmd_methods(args)
368
+ return 0
369
+ s = config.resolve(args.host, args.user, args.config)
370
+ with Router(s.host, s.user, s.password, timeout=args.timeout, verify_tls=not args.insecure,
371
+ dry_run=args.dry_run) as router:
372
+ HANDLERS[args.command](args, router)
373
+ return 0
374
+ except IptimeError as exc:
375
+ print(f"error: {exc}", file=sys.stderr)
376
+ return 1
377
+ except json.JSONDecodeError as exc:
378
+ print(f"error: params are not valid JSON: {exc}", file=sys.stderr)
379
+ return 2
380
+ except KeyboardInterrupt:
381
+ return 130
382
+
383
+
384
+ if __name__ == "__main__":
385
+ raise SystemExit(main())