secraft 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.
secraft/__init__.py ADDED
@@ -0,0 +1,56 @@
1
+ """secraft simplifies the security workflow.
2
+
3
+ import secraft as sec
4
+
5
+ r = sec.portscan("192.168.1.1")
6
+ print(r)
7
+ if 22 in r.ports:
8
+ sec.ssh("192.168.1.1", user="root", wordlist="pass.txt")
9
+
10
+ Port scanning, service banners, web probing, DNS recon, credential checks and
11
+ raw packets are each one call here, and each returns the same Result object
12
+ with three clear states (done / done-but-empty / failed). A one-off script no
13
+ longer needs five libraries and five ways of deciding whether the thing it just
14
+ did actually worked.
15
+
16
+ Three design rules: one function is one scenario; every action returns Result,
17
+ so print(r) always works; a failure says why it failed and what to try next.
18
+
19
+ Use it only on hosts you own or are authorized to test.
20
+ """
21
+
22
+ from . import brute
23
+ from . import crypto
24
+ from . import net as _net
25
+ from . import recon as _recon
26
+ from . import web as _web
27
+ from .brute import (ftp, http_basic, http_form, imap, ldap, mongodb, mssql,
28
+ mysql, pop3, postgres, redis, smb, smtp, ssh, telnet)
29
+ from .ledger import clear as clear_log
30
+ from .ledger import log, records, report
31
+ from .batch import Batch
32
+ from .net import (TCP, UDP, banner, fingerprint, identify, parse_ports, ping,
33
+ portscan, synscan, tcp, udp)
34
+ from .recon import dns, subdomain
35
+ from .result import Result, Status
36
+ from . import cli, jwt
37
+ from .util import codec, text, wordlist
38
+ from .web import csrf, fuzz, http, raw, serve
39
+
40
+ __version__ = "0.1.0"
41
+
42
+ __all__ = [
43
+ "Result", "Status", "Batch",
44
+ "portscan", "synscan", "banner", "ping", "fingerprint", "identify",
45
+ "parse_ports",
46
+ "http", "raw", "fuzz", "csrf", "serve",
47
+ "tcp", "udp", "TCP", "UDP",
48
+ "dns", "subdomain",
49
+ "brute", "ssh", "ftp", "smtp", "pop3", "imap", "telnet", "redis",
50
+ "mysql", "postgres", "mongodb", "smb", "ldap", "mssql",
51
+ "http_basic", "http_form",
52
+ "crypto", "jwt",
53
+ "codec", "text", "wordlist",
54
+ "log", "report", "records", "clear_log",
55
+ "__version__",
56
+ ]
secraft/_guard.py ADDED
@@ -0,0 +1,136 @@
1
+ """Outer guard: turn any surprise into a Result, never let exceptions escape."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import inspect
7
+ import math
8
+ from typing import Any, Callable
9
+
10
+ from .ledger import emit
11
+ from .result import Result, Status
12
+
13
+ __all__ = ["guard", "as_port", "as_timeout", "as_workers", "as_int",
14
+ "as_delay", "ProgrammingError"]
15
+
16
+
17
+ class ProgrammingError(TypeError):
18
+ """A mistake in the caller's code (wrong keyword, bad argument).
19
+
20
+ The guard turns unexpected exceptions into Results, but this one is a bug
21
+ in the script, not a condition to report: it must reach the user as a
22
+ traceback instead of a Result nobody prints.
23
+ """
24
+
25
+ _HINT = (
26
+ "check the arguments: port 1-65535, timeout > 0, "
27
+ "URL needs http:// or https://"
28
+ )
29
+
30
+
31
+ def guard(action: str = "", target_index: int = 0) -> Callable:
32
+ """Turn unexpected exceptions into Result(ERROR).
33
+
34
+ target_index picks which positional argument is "the target" for
35
+ attribution in log/report; don't guess with args[0] -- http.request's
36
+ first argument is the method, not the URL.
37
+ """
38
+
39
+ def decorator(func: Callable) -> Callable:
40
+ try:
41
+ signature = inspect.signature(func)
42
+ except (TypeError, ValueError): # pragma: no cover - builtins etc.
43
+ signature = None
44
+
45
+ @functools.wraps(func)
46
+ def wrapper(*args: Any, **kwargs: Any) -> Result:
47
+ # A wrong keyword or a missing argument is a bug in *your* script,
48
+ # not an environment problem: fail loudly instead of returning a
49
+ # Result nobody prints. (This is how "wordlists=" used to vanish.)
50
+ if signature is not None:
51
+ try:
52
+ signature.bind(*args, **kwargs)
53
+ except TypeError as exc:
54
+ raise ProgrammingError(f"{func.__name__}: {exc}") from None
55
+ try:
56
+ return func(*args, **kwargs)
57
+ except ProgrammingError:
58
+ raise
59
+ except (ValueError, TypeError, OverflowError, OSError,
60
+ UnicodeError, ImportError, RuntimeError) as exc: # noqa: BLE001
61
+ target = ""
62
+ if len(args) > target_index:
63
+ target = args[target_index]
64
+ else:
65
+ for key in ("target", "url", "host", "name", "domain"):
66
+ if key in kwargs:
67
+ target = kwargs[key]
68
+ break
69
+ return emit(Result(
70
+ action=action or func.__name__,
71
+ target=str(target),
72
+ status=Status.ERROR,
73
+ error=f"{type(exc).__name__}: {exc}",
74
+ hint=_HINT,
75
+ ))
76
+
77
+ return wrapper
78
+
79
+ return decorator
80
+
81
+
82
+ # ---------------------------------------------------------------- validation
83
+ def as_int(value: Any, name: str, low: int, high: int) -> int:
84
+ if isinstance(value, bool):
85
+ raise ValueError(f"{name} can't be a bool")
86
+ if isinstance(value, float):
87
+ if not value.is_integer():
88
+ raise ValueError(f"{name} must be an integer, got {value!r}")
89
+ value = int(value)
90
+ try:
91
+ number = int(value)
92
+ except (TypeError, ValueError):
93
+ raise ValueError(f"{name} must be an integer, got {value!r}") from None
94
+ if number < low or number > high:
95
+ raise ValueError(f"{name} must be between {low} and {high}, got {number}")
96
+ return number
97
+
98
+
99
+ def as_port(value: Any, name: str = "port", allow_zero: bool = False) -> int:
100
+ low = 0 if allow_zero else 1
101
+ return as_int(value, name, low, 65535)
102
+
103
+
104
+ def as_timeout(value: Any, name: str = "timeout", default: float = 10.0) -> float:
105
+ if value is None:
106
+ return default
107
+ try:
108
+ number = float(value)
109
+ except (TypeError, ValueError):
110
+ raise ValueError(f"{name} must be a number, got {value!r}") from None
111
+ if not math.isfinite(number):
112
+ raise ValueError(f"{name} must be a finite number, got {value}")
113
+ if number <= 0:
114
+ raise ValueError(f"{name} must be greater than 0, got {value}")
115
+ return number
116
+
117
+
118
+ def as_workers(value: Any, default: int = 50, maximum: int = 1000) -> int:
119
+ if value is None:
120
+ return default
121
+ return as_int(value, "workers", 1, maximum)
122
+
123
+
124
+ def as_delay(value: Any, default: float = 0.0) -> float:
125
+ """Delay between attempts: non-negative and finite."""
126
+ if value is None:
127
+ return default
128
+ try:
129
+ number = float(value)
130
+ except (TypeError, ValueError):
131
+ raise ValueError(f"delay must be a number, got {value!r}") from None
132
+ if not math.isfinite(number):
133
+ raise ValueError(f"delay must be a finite number, got {value}")
134
+ if number < 0:
135
+ raise ValueError(f"delay can't be negative, got {number}")
136
+ return number
secraft/batch.py ADDED
@@ -0,0 +1,457 @@
1
+ """Batch —— what a call returns when it was given many targets.
2
+
3
+ A single-target call keeps returning `Result`; only a multi-target call
4
+ returns `Batch`. Batch is deliberately not a Result subclass: "which hosts
5
+ have 22 open" and "is 22 in this result" are different questions, and a
6
+ flattened ``ports`` list would answer the second one wrongly.
7
+
8
+ b = sec.portscan(["10.0.0.1", "10.0.0.2"])
9
+ b.items # [Result, Result]
10
+ b.open_ports # {"10.0.0.1": [22, 80]}
11
+ b.counts # {"ok": 1, "empty": 1, "error": 0}
12
+ b.partial # True when the targets did not all end the same way
13
+ "10.0.0.1" in b # target membership, not port membership
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ import re
20
+ import time
21
+ from typing import Any, Dict, Iterator, List, Optional
22
+
23
+ from .ledger import emit
24
+ from .result import Result, Status
25
+
26
+ __all__ = ["Batch", "as_targets"]
27
+
28
+
29
+ def as_targets(value: Any) -> List[str]:
30
+ """Normalise "some targets" into a list of strings.
31
+
32
+ Accepts a single string (one host or CIDR), a path to a file with one
33
+ target per line, or any iterable of strings. A bare string is one target,
34
+ never split into characters.
35
+ """
36
+ if isinstance(value, str):
37
+ text = value.strip()
38
+ if not text:
39
+ raise ValueError("target list is empty")
40
+ if os.path.isfile(text):
41
+ with open(text, "rb") as fh:
42
+ raw = fh.read()
43
+ decoded = None
44
+ for encoding in ("utf-8-sig", "utf-8", "gbk"):
45
+ try:
46
+ decoded = raw.decode(encoding)
47
+ break
48
+ except UnicodeDecodeError:
49
+ continue
50
+ if decoded is None:
51
+ raise ValueError(
52
+ f"cannot decode {value}: not utf-8 or gbk text")
53
+ items = [line.strip() for line in decoded.splitlines()
54
+ if line.strip() and not line.strip().startswith("#")]
55
+ if not items:
56
+ raise ValueError(f"target file has no usable lines: {value}")
57
+ return items
58
+ return [text]
59
+ if isinstance(value, (bytes, bytearray)):
60
+ return [bytes(value).decode("utf-8", "replace")]
61
+ try:
62
+ items = [str(item).strip() for item in value]
63
+ except TypeError:
64
+ raise ValueError(f"cannot read targets from {type(value).__name__}") from None
65
+ items = [item for item in items if item]
66
+ if not items:
67
+ raise ValueError("target list is empty")
68
+ return items
69
+
70
+
71
+ class Batch:
72
+ """Many single-target Results, plus the aggregate views that make sense."""
73
+
74
+ def __init__(self, action: str, items: List[Result],
75
+ started: Optional[float] = None,
76
+ params: Optional[dict] = None):
77
+ self.action = action
78
+ self.items: List[Result] = list(items)
79
+ self.params: Dict[str, Any] = dict(params or {})
80
+ self.started = started if started is not None else time.perf_counter()
81
+ self.elapsed = max((item.elapsed for item in self.items), default=0.0)
82
+
83
+ # ---------------------------------------------------------------- state
84
+ @property
85
+ def status(self) -> str:
86
+ """Aggregate state: error only if every target errored, and so on."""
87
+ if not self.items:
88
+ return Status.EMPTY
89
+ statuses = {item.status for item in self.items}
90
+ if statuses == {Status.ERROR}:
91
+ return Status.ERROR
92
+ if statuses == {Status.EMPTY}:
93
+ return Status.EMPTY
94
+ return Status.OK
95
+
96
+ @property
97
+ def ok(self) -> bool:
98
+ return self.status != Status.ERROR
99
+
100
+ @property
101
+ def failed(self) -> bool:
102
+ return self.status == Status.ERROR
103
+
104
+ @property
105
+ def partial(self) -> bool:
106
+ """True when the targets did not all end the same way."""
107
+ return len({item.status for item in self.items}) > 1
108
+
109
+ @property
110
+ def counts(self) -> Dict[str, int]:
111
+ out = {Status.OK: 0, Status.EMPTY: 0, Status.ERROR: 0}
112
+ for item in self.items:
113
+ out[item.status] = out.get(item.status, 0) + 1
114
+ return out
115
+
116
+ @property
117
+ def failures(self) -> List[Result]:
118
+ return [item for item in self.items if item.status == Status.ERROR]
119
+
120
+ # ---------------------------------------------------------------- views
121
+ @property
122
+ def open_ports(self) -> Dict[str, List[int]]:
123
+ """host -> open ports. The only correct way to ask about ports."""
124
+ out: Dict[str, List[int]] = {}
125
+ for item in self.items:
126
+ host = _host_of(item)
127
+ ports = item.ports
128
+ if ports:
129
+ out[host] = ports
130
+ return out
131
+
132
+ @property
133
+ def data(self) -> List[dict]:
134
+ """Flattened rows, each tagged with its host, for report building."""
135
+ rows: List[dict] = []
136
+ for item in self.items:
137
+ host = _host_of(item)
138
+ if isinstance(item.data, list):
139
+ for row in item.data:
140
+ if isinstance(row, dict):
141
+ rows.append({**row, "host": row.get("host", host)})
142
+ elif item.data is not None:
143
+ rows.append({"host": host, "data": item.data})
144
+ return rows
145
+
146
+ @property
147
+ def targets(self) -> List[str]:
148
+ return [_host_of(item) for item in self.items]
149
+
150
+ def __iter__(self) -> Iterator[Result]:
151
+ return iter(self.items)
152
+
153
+ def __len__(self) -> int:
154
+ return len(self.items)
155
+
156
+ def __getitem__(self, key: Any) -> Result:
157
+ if isinstance(key, int):
158
+ return self.items[key]
159
+ for item in self.items:
160
+ if item.target == key or _host_of(item) == key:
161
+ return item
162
+ raise KeyError(key)
163
+
164
+ def __contains__(self, key: Any) -> bool:
165
+ """Membership means "this target is in the batch", not "this port"."""
166
+ return any(item.target == key or _host_of(item) == key
167
+ for item in self.items)
168
+
169
+ def __bool__(self) -> bool:
170
+ return any(item.ok for item in self.items)
171
+
172
+ # ---------------------------------------------------------------- display
173
+ def summary(self) -> str:
174
+ counts = self.counts
175
+ return (f"{len(self.items)} target(s): {counts[Status.OK]} with a result, "
176
+ f"{counts[Status.EMPTY]} empty, {counts[Status.ERROR]} failed")
177
+
178
+ def render(self, limit: int = 20) -> str:
179
+ head = f"── {self.action} batch ({len(self.items)} targets)"
180
+ lines = [head, " " + self.summary()]
181
+ if self.partial:
182
+ lines.append(" partial: targets did not all end the same way")
183
+ open_ports = self.open_ports
184
+ for item in self.items[:limit]:
185
+ host = _host_of(item)
186
+ ports = open_ports.get(host)
187
+ detail = (" ".join(str(p) for p in ports) if ports
188
+ else (item.message or item.error or item.status))
189
+ lines.append(f" {host:<20} {item.status:<6} {detail}")
190
+ if len(self.items) > limit:
191
+ lines.append(f" ... and {len(self.items) - limit} more")
192
+ return "\n".join(lines)
193
+
194
+ def __str__(self) -> str:
195
+ return self.render()
196
+
197
+ def __repr__(self) -> str:
198
+ return f"Batch(action={self.action!r}, n={len(self.items)}, " \
199
+ f"partial={self.partial})"
200
+
201
+ # ---------------------------------------------------------------- export
202
+ def table(self, columns: Optional[List[str]] = None, max_col: int = 48,
203
+ limit: Optional[int] = None) -> str:
204
+ """Aligned table of every row, each tagged with its host."""
205
+ rows = self.data
206
+ if not rows:
207
+ return self.render(limit=limit or 20)
208
+ return Result(action=self.action, target=f"{len(self.items)} targets",
209
+ status=self.status, data=rows).table(
210
+ columns=columns, max_col=max_col, limit=limit)
211
+
212
+ def to_dict(self) -> dict:
213
+ return {
214
+ "action": self.action,
215
+ "params": dict(self.params),
216
+ "counts": self.counts,
217
+ "partial": self.partial,
218
+ "items": [item.to_dict() for item in self.items],
219
+ }
220
+
221
+
222
+ _CIDR_SHAPE = re.compile(r"^[\d.]+/\d+$")
223
+ _RANGE_SHAPE = re.compile(r"^[\d.]+-[\d.]+$")
224
+ _NUMERIC = re.compile(r"^[\d.]+$")
225
+
226
+
227
+ def _is_url(text: str) -> bool:
228
+ return "://" in text or text.startswith("//")
229
+
230
+
231
+ def _looks_like_cidr(text: str) -> bool:
232
+ if _is_url(text):
233
+ return False
234
+ if _CIDR_SHAPE.match(text):
235
+ return True
236
+ if ":" in text and "/" in text:
237
+ return True # IPv6 CIDR: refuses with a reason
238
+ if "/" in text:
239
+ # "1.2.3.4/abc" is a broken network, not a hostname.
240
+ return bool(_NUMERIC.match(text.split("/", 1)[0].strip()))
241
+ return False
242
+
243
+
244
+ def _looks_like_range(text: str) -> bool:
245
+ if _is_url(text):
246
+ return False
247
+ if _RANGE_SHAPE.match(text):
248
+ return True
249
+ if text.startswith("-"):
250
+ return bool(_NUMERIC.match(text[1:].strip() or "x"))
251
+ if "-" not in text:
252
+ return False
253
+ # "1.2.3.4-abc" and "1.2.3.4-" are broken ranges; "my-host" is not.
254
+ return bool(_NUMERIC.match(text.split("-", 1)[0].strip()))
255
+
256
+
257
+ def _expand_cidr(text: str, limit: int = 256) -> List[str]:
258
+ """Expand a CIDR block; a malformed one is an error, never a hostname."""
259
+ import ipaddress
260
+
261
+ try:
262
+ net = ipaddress.ip_network(text, strict=False)
263
+ except ValueError as exc:
264
+ raise ValueError(f"bad network {text}: {exc}") from None
265
+ if net.version == 6:
266
+ raise ValueError("IPv6 networks are not supported yet")
267
+ # Check the size before materialising: a /8 would otherwise build a
268
+ # sixteen-million-entry list just to reject it.
269
+ if net.num_addresses > limit + 2:
270
+ raise ValueError(
271
+ f"{text} has {net.num_addresses} addresses; at most {limit} at a "
272
+ f"time, split it up")
273
+ hosts = [str(ip) for ip in net.hosts()] or [str(net.network_address)]
274
+ if len(hosts) > limit:
275
+ raise ValueError(
276
+ f"{text} has {len(hosts)} usable addresses; at most {limit} at a "
277
+ f"time, split it up")
278
+ return hosts
279
+
280
+
281
+ def _expand_range(text: str, limit: int = 256) -> List[str]:
282
+ """Expand "10.0.0.1-20" or "10.0.0.1-10.0.0.20"; bad input raises."""
283
+ left, right = text.split("-", 1)
284
+ left, right = left.strip(), right.strip()
285
+ try:
286
+ start = [int(part) for part in left.split(".")]
287
+ end = ([int(part) for part in right.split(".")]
288
+ if right.count(".") == 3 else start[:3] + [int(right)])
289
+ except ValueError:
290
+ raise ValueError(f"bad address range {text}") from None
291
+ if len(start) != 4 or len(end) != 4 or any(
292
+ not 0 <= part <= 255 for part in start + end):
293
+ raise ValueError(f"bad address range {text}: octets must be 0-255")
294
+ begin = (start[0] << 24) | (start[1] << 16) | (start[2] << 8) | start[3]
295
+ last = (end[0] << 24) | (end[1] << 16) | (end[2] << 8) | end[3]
296
+ if last < begin:
297
+ raise ValueError(f"{text}: the range ends before it starts")
298
+ if last - begin + 1 > limit:
299
+ raise ValueError(f"{text} spans more than {limit} addresses; "
300
+ f"split it up")
301
+ return [f"{(n >> 24) & 255}.{(n >> 16) & 255}.{(n >> 8) & 255}.{n & 255}"
302
+ for n in range(begin, last + 1)]
303
+
304
+
305
+ def expand_targets(value: Any) -> List[str]:
306
+ """Normalise targets and expand CIDR blocks and address ranges.
307
+
308
+ Accepts everything ``as_targets`` accepts, and additionally:
309
+
310
+ 192.168.1.0/24 a network (up to 256 hosts)
311
+ 10.0.0.5-10 a short range on the last octet
312
+ 10.0.0.5-10.0.0.20 a full range
313
+
314
+ Something shaped like a network or a range but written wrongly (a /33, an
315
+ octet of 999) raises ValueError instead of being treated as a hostname.
316
+ Anything else is passed through unchanged (a hostname, a URL, "host:port").
317
+ """
318
+ items = as_targets(value)
319
+ out: List[str] = []
320
+ for item in items:
321
+ if _looks_like_cidr(item):
322
+ out.extend(_expand_cidr(item))
323
+ elif _looks_like_range(item):
324
+ out.extend(_expand_range(item))
325
+ else:
326
+ out.append(item)
327
+ return out
328
+
329
+
330
+ def is_multi(value: Any) -> bool:
331
+ """True when this target needs the batch path rather than one call.
332
+
333
+ A plain host string is single; a list, a file, a CIDR block or an address
334
+ range is not. URLs (including protocol-relative ones) are always single.
335
+ """
336
+ if not isinstance(value, str):
337
+ return True
338
+ text = value.strip()
339
+ if "://" in text or text.startswith("//"):
340
+ return False # a URL is one target, its path is not a network
341
+ if os.path.isfile(text):
342
+ return True
343
+ return _looks_like_cidr(text) or _looks_like_range(text)
344
+
345
+
346
+ def _host_of(item: Result) -> str:
347
+ """The key for this item: a host, or the whole URL when it is one."""
348
+ text = item.target
349
+ if "://" in text:
350
+ return text
351
+ head = text.split(" ", 1)[0] # "localhost (127.0.0.1)" -> "localhost"
352
+ if head.startswith("["):
353
+ end = head.find("]")
354
+ return head[1:end] if end > 0 else head
355
+ if head.count(":") == 1:
356
+ return head.split(":", 1)[0]
357
+ return head
358
+
359
+
360
+ def _split_host_port(target: str):
361
+ """Split "host:port" / "[v6]:port"; returns (host, port or None)."""
362
+ if target.startswith("["):
363
+ end = target.find("]")
364
+ if end > 0:
365
+ host = target[1:end]
366
+ rest = target[end + 1:]
367
+ if rest.startswith(":") and rest[1:].isdigit():
368
+ return host, int(rest[1:])
369
+ return host, None
370
+ if target.count(":") == 1:
371
+ host, _, port = target.partition(":")
372
+ if port.isdigit():
373
+ return host, int(port)
374
+ return target, None
375
+
376
+
377
+ def multi_target(func):
378
+ """Let a single-target function accept a list of targets or a file.
379
+
380
+ Wraps a function whose first argument is the target. One target behaves
381
+ exactly as before; many return a Batch. Each item already records itself,
382
+ so only the batch summary is added to the ledger.
383
+
384
+ A list entry may carry its own port ("10.0.0.5:2222"); an explicit
385
+ ``port=`` argument wins over it. CIDR blocks and "a.b.c.1-20" ranges are
386
+ expanded first, so a subnet sweep is one call. A bad target list is
387
+ reported as a
388
+ failed Result, never raised: every public function answers with a Result.
389
+ """
390
+ import functools
391
+
392
+ @functools.wraps(func)
393
+ def wrapper(host, *args, **kwargs):
394
+ single = not is_multi(host)
395
+ if single:
396
+ host_only, port = _split_host_port(host.strip())
397
+ call_kwargs = dict(kwargs)
398
+ if port is not None and "port" not in call_kwargs:
399
+ call_kwargs["port"] = port
400
+ return func(host_only, *args, **call_kwargs)
401
+ try:
402
+ targets = expand_targets(host)
403
+ except (ValueError, OSError) as exc:
404
+ return emit(Result(
405
+ action=func.__name__, target=str(host), status=Status.ERROR,
406
+ error=str(exc),
407
+ hint="pass a host, a list of hosts, or a file with one per "
408
+ "line",
409
+ ))
410
+ explicit_batch = not isinstance(host, str) or os.path.isfile(
411
+ host.strip())
412
+ if len(targets) == 1 and not explicit_batch:
413
+ # "10.0.0.1/32" and "10.0.0.1-1" are one host written the long way;
414
+ # the shape of the answer follows the number of hosts, not the
415
+ # syntax that produced it.
416
+ host_only, port = _split_host_port(targets[0])
417
+ call_kwargs = dict(kwargs)
418
+ if port is not None and "port" not in call_kwargs:
419
+ call_kwargs["port"] = port
420
+ return func(host_only, *args, **call_kwargs)
421
+ started = time.perf_counter()
422
+ items = []
423
+ for target in targets:
424
+ host_only, port = _split_host_port(target)
425
+ call_kwargs = dict(kwargs)
426
+ if port is not None and "port" not in call_kwargs:
427
+ call_kwargs["port"] = port
428
+ items.append(func(host_only, *args, **call_kwargs))
429
+ action = items[0].action if items else func.__name__
430
+ batch = Batch(action, items, started)
431
+ emit(_summary_result(batch, None))
432
+ return batch
433
+
434
+ return wrapper
435
+
436
+
437
+ def record(batch: Batch, params: Optional[dict] = None) -> Batch:
438
+ """Put every item and one summary record into the ledger."""
439
+ if params:
440
+ batch.params.update(params)
441
+ for item in batch.items:
442
+ emit(item)
443
+ emit(_summary_result(batch, params))
444
+ return batch
445
+
446
+
447
+ def _summary_result(batch: Batch, params: Optional[dict]) -> Result:
448
+ counts = batch.counts
449
+ return Result(
450
+ action=f"{batch.action}.batch",
451
+ target=f"{len(batch.items)} targets",
452
+ status=batch.status,
453
+ data={"targets": len(batch.items), **counts},
454
+ message=batch.summary(),
455
+ engine="batch",
456
+ params=params or {},
457
+ )