bind-zone-sync 0.2.1__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.
File without changes
@@ -0,0 +1,457 @@
1
+ #!/usr/bin/env python3
2
+ """bind-zone-sync gen | restore | catalog
3
+
4
+ gen write a secondary-zone config from a primary-zone config
5
+ restore convert a secondary-zone config back to a primary-zone config
6
+ catalog build a catalog.zone zone list from named.conf with SHA1 keys
7
+ """
8
+
9
+ import argparse
10
+ import hashlib
11
+ import ipaddress
12
+ import logging
13
+ import re
14
+ from pathlib import Path, PurePosixPath
15
+
16
+ logger = logging.getLogger("bind-zone-sync")
17
+
18
+
19
+ def parse_args() -> argparse.Namespace:
20
+ p = argparse.ArgumentParser(
21
+ description="Manage BIND zones configuration.",
22
+ formatter_class=argparse.RawDescriptionHelpFormatter,
23
+ epilog=__doc__,
24
+ )
25
+ p.add_argument("command", choices=["gen", "restore", "convert", "catalog"],
26
+ help="gen = write secondary-zone config; restore = convert secondary config back to primary; convert = build legacy named.conf from zone db files folder; catalog = build catalog.zone zone list from named.conf with SHA1 keys")
27
+
28
+ p.add_argument("--conf", default="/usr/local/etc/namedb/zones-primary.conf.auto",
29
+ help="Input zone config file (default: %(default)s)")
30
+ p.add_argument("--out", default="/usr/local/etc/namedb/zones-secondary.conf.auto",
31
+ help="Output zone config file (default: %(default)s)")
32
+ p.add_argument("--primaries", default="",
33
+ help="Full content for the primaries directive; when set, generates secondary zones; when omitted, generates primary zones (default: empty = primary)")
34
+ p.add_argument("--db-path-find", default="/usr/local/etc/namedb/primary/",
35
+ help="Path prefix in zone file paths to replace (default: %(default)s)")
36
+ p.add_argument("--db-path-replace", default="",
37
+ help="Replacement path prefix for secondary zone files; empty = keep original (default: keep)")
38
+ p.add_argument("--comment", default="// generated by bind-zone-sync, do not edit",
39
+ help="Comment header line in the output file (default: %(default)s)")
40
+ p.add_argument("--log-level", default="INFO",
41
+ choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
42
+ help="Logging level (default: %(default)s)")
43
+
44
+ return p.parse_args()
45
+
46
+
47
+ # zones that stay local on every server (compared lowercase, without trailing dot)
48
+ EXCLUDE = {
49
+ "localhost",
50
+ "0.0.127.in-addr.arpa",
51
+ "127.in-addr.arpa",
52
+ "255.in-addr.arpa",
53
+ "0.in-addr.arpa",
54
+ ipaddress.ip_address("::1").reverse_pointer, # exact 32-nibble name
55
+ }
56
+ EXCLUDE_FILE_PREFIXES = () # e.g. ("/usr/local/etc/namedb/local/",)
57
+
58
+ ZONE_PRIMARY_TYPES = {"primary", "master"}
59
+ ZONE_SECONDARY_TYPES = {"secondary", "slave"}
60
+
61
+ # Pre-compiled regular expressions
62
+ ORIGIN_DIRECTIVE_PATTERN: re.Pattern[str] = re.compile(
63
+ r"^\s*\$ORIGIN\s+(\S+)", re.MULTILINE | re.IGNORECASE
64
+ )
65
+ SOA_OWNER_PATTERN: re.Pattern[str] = re.compile(
66
+ r"^(\S+)\s+IN\s+SOA\b", re.MULTILINE | re.IGNORECASE
67
+ )
68
+ DIRECTORY_DIRECTIVE_PATTERN: re.Pattern[str] = re.compile(
69
+ r'^\s*directory\s+"([^"]+)"', re.MULTILINE
70
+ )
71
+ ZONE_BLOCK_PATTERN: re.Pattern[str] = re.compile(
72
+ r'zone\s+"([^"]+)"(?:\s+\w+)?\s*\{'
73
+ )
74
+ ZONE_TYPE_PATTERN: re.Pattern[str] = re.compile(
75
+ r'type\s+(\w+)'
76
+ )
77
+ ZONE_FILE_PATTERN: re.Pattern[str] = re.compile(
78
+ r'file\s+"([^"]+)"'
79
+ )
80
+ PRIMARIES_DIRECTIVE_PATTERN: re.Pattern[str] = re.compile(
81
+ r'^\s*primaries\s+\{'
82
+ )
83
+ FILE_PATH_PATTERN: re.Pattern[str] = re.compile(
84
+ r'^(\s*file\s+")([^"]+)(".*)$'
85
+ )
86
+
87
+
88
+ def _build_type_pattern(source_types: set[str]) -> re.Pattern[str]:
89
+ """Build a compiled regex pattern for matching zone type directives."""
90
+ return re.compile(r'^(\s*)type\s+(' + '|'.join(source_types) + r')\s*;')
91
+
92
+
93
+ def extract_zone_from_soa(db_file: str) -> str | None:
94
+ """Extract the zone name from a BIND zone db file's SOA record.
95
+
96
+ Tries two methods in order:
97
+ 1. $ORIGIN directive — the most reliable source of the zone name.
98
+ 2. SOA owner name — the name before 'IN SOA' (typically '@' which resolves via $ORIGIN,
99
+ or the full zone name).
100
+
101
+ Returns the zone name without trailing dot, or None if no SOA found.
102
+ """
103
+ path = Path(db_file)
104
+ if not path.exists():
105
+ logger.error(f"DB file {db_file} does not exist")
106
+ return None
107
+ try:
108
+ txt = path.read_text(encoding="utf-8")
109
+ except OSError as e:
110
+ logger.error(f"Cannot read DB file {db_file}: {e}")
111
+ return None
112
+
113
+ # Method 1: $ORIGIN directive
114
+ origin_match = ORIGIN_DIRECTIVE_PATTERN.search(txt)
115
+ if origin_match:
116
+ zone = origin_match.group(1).rstrip(".").rstrip(";").strip()
117
+ if zone and zone != "@":
118
+ return zone.lower()
119
+
120
+ # Method 2: SOA owner name
121
+ soa_match = SOA_OWNER_PATTERN.search(txt)
122
+ if soa_match:
123
+ owner = soa_match.group(1).rstrip(".").rstrip(";").strip()
124
+ if owner and owner != "@":
125
+ return owner.lower()
126
+
127
+ return None
128
+
129
+
130
+ def _parse_zones_from_file(conf: str, zone_types: set[str]) -> tuple[str, list[tuple[str, str, int, str]]]:
131
+ """Parse zones from a config file, filtering by the given zone types.
132
+
133
+ Returns (directory_base, zones_list) where:
134
+ - directory_base is the value of the directory directive (empty string if absent)
135
+ - zones_list is [(zone_name, file_path, line_number, block_text)] for matching zones.
136
+ file_path is the original path from the config (relative kept relative).
137
+ line_number is the 1-based line in the config file where the zone block starts.
138
+ block_text is the full original zone block text (from 'zone' to '};' inclusive).
139
+ """
140
+ conf = Path(conf)
141
+ if not conf.exists():
142
+ logger.error(f"Config file {conf} does not exist")
143
+ return "", []
144
+ try:
145
+ txt = conf.read_text(encoding="utf-8")
146
+ except OSError as e:
147
+ logger.error(f"Cannot read config file {conf}: {e}")
148
+ return "", []
149
+
150
+ # Try to find a directory directive; if absent, use empty string (absolute paths only)
151
+ d = DIRECTORY_DIRECTIVE_PATTERN.search(txt)
152
+ base = d.group(1) if d else ""
153
+
154
+ zones = []
155
+ for m in ZONE_BLOCK_PATTERN.finditer(txt):
156
+ name = m.group(1).rstrip(".").lower()
157
+ if not name or name in EXCLUDE:
158
+ logger.debug(f"Skipping zone {name}: excluded")
159
+ continue
160
+ depth, i = 1, m.end()
161
+ while depth:
162
+ depth += {"{": 1, "}": -1}.get(txt[i], 0)
163
+ i += 1
164
+ # Include trailing semicolon after closing brace
165
+ end = i
166
+ rest = txt[end:].lstrip()
167
+ if rest.startswith(";"):
168
+ end += len(txt[end:]) - len(rest) + 1
169
+ body = txt[m.end():i]
170
+ t = ZONE_TYPE_PATTERN.search(body)
171
+ f = ZONE_FILE_PATTERN.search(body)
172
+ if not (t and t.group(1).lower() in zone_types and f):
173
+ logger.debug(f"Skipping zone {name}: type not in {zone_types}")
174
+ continue
175
+ path = f.group(1)
176
+ if path.startswith(EXCLUDE_FILE_PREFIXES):
177
+ logger.debug(f"Skipping zone {name}: file path starts with excluded prefix")
178
+ continue
179
+ line_no = txt[:m.start()].count("\n") + 1
180
+ block_text = txt[m.start():end]
181
+ zones.append((m.group(1), path, line_no, block_text))
182
+ return (base, zones)
183
+
184
+
185
+ def parse_primary_zones_from_file(conf: str, zone_types: set[str] | None = None) -> tuple[str, list[tuple[str, str, int, str]]]:
186
+ """Parse primary/master zones from a config file. Returns (directory_base, zones_list)."""
187
+ return _parse_zones_from_file(conf, zone_types or ZONE_PRIMARY_TYPES)
188
+
189
+
190
+ def parse_secondary_zones_from_file(conf: str, zone_types: set[str] | None = None) -> tuple[str, list[tuple[str, str, int, str]]]:
191
+ """Parse secondary/slave zones from a config file. Returns (directory_base, zones_list)."""
192
+ return _parse_zones_from_file(conf, zone_types or ZONE_SECONDARY_TYPES)
193
+
194
+
195
+ def _transform_zone_block(block_text: str, file_path: str, source_types: set[str], target_type: str,
196
+ add_primaries: bool | None = None, primaries_content: str = "") -> str:
197
+ """Transform a zone block from one type to another.
198
+
199
+ Preserves the original multi-line format, indentation, and comments.
200
+
201
+ Parameters:
202
+ block_text: The original zone block text.
203
+ file_path: The zone file path (already substituted if needed).
204
+ source_types: Set of source type names to match (e.g., {"primary", "master"}).
205
+ target_type: The target type name (e.g., "secondary").
206
+ add_primaries: If True, insert a primaries directive after the type line.
207
+ primaries_content: Full content string for the primaries directive (e.g., "10.0.0.100;").
208
+ """
209
+
210
+ lines = block_text.split("\n")
211
+ result_lines = []
212
+ directive_added = False
213
+ i = 0
214
+ while i < len(lines):
215
+ line = lines[i]
216
+ stripped = line.strip()
217
+
218
+ # Handle the closing '};' — insert directive before it if not yet added
219
+ if stripped == '};':
220
+ indent = lines[0][:len(lines[0]) - len(lines[0].lstrip())] if lines[0].lstrip() else " "
221
+ if add_primaries and not directive_added and primaries_content:
222
+ result_lines.append(f'{indent}type {target_type};')
223
+ result_lines.append(f'{indent}primaries {{ {primaries_content} }};')
224
+ directive_added = True
225
+ result_lines.append('};')
226
+ i += 1
227
+ continue
228
+
229
+ # Replace source type with target type
230
+ type_match = _build_type_pattern(source_types).match(line)
231
+ if type_match:
232
+ indent = type_match.group(1)
233
+ result_lines.append(f'{indent}type {target_type};')
234
+ if add_primaries and primaries_content:
235
+ result_lines.append(f'{indent}primaries {{ {primaries_content} }};')
236
+ directive_added = True
237
+ i += 1
238
+ continue
239
+
240
+ # Skip the primaries directive when removing it
241
+ if not add_primaries and PRIMARIES_DIRECTIVE_PATTERN.match(stripped):
242
+ i += 1
243
+ continue
244
+
245
+ # Update file path if present
246
+ file_match = FILE_PATH_PATTERN.match(line)
247
+ if file_match:
248
+ result_lines.append(f'{file_match.group(1)}{file_path}{file_match.group(3)}')
249
+ i += 1
250
+ continue
251
+
252
+ # Keep all other lines as-is (allow-query, comments, etc.)
253
+ result_lines.append(line)
254
+ i += 1
255
+
256
+ return "\n".join(result_lines)
257
+
258
+
259
+ def _convert(args: argparse.Namespace, zone_types: set[str], target_type: str, add_primaries: bool, comment: str) -> None:
260
+ """Shared logic for gen and restore: parse, transform, and write zone config.
261
+
262
+ Parameters:
263
+ args: Parsed CLI arguments.
264
+ zone_types: Set of source zone types to filter (e.g., {"primary", "master"}).
265
+ target_type: Target type name (e.g., "secondary").
266
+ add_primaries: If True, insert primaries directive; if False, remove it.
267
+ comment: Comment header line for the output file.
268
+ """
269
+ # Choose parser based on zone types
270
+ if zone_types == ZONE_PRIMARY_TYPES:
271
+ directory_base, zones = parse_primary_zones_from_file(args.conf)
272
+ else:
273
+ directory_base, zones = parse_secondary_zones_from_file(args.conf)
274
+
275
+ # Read the original config to preserve blank lines between zone blocks
276
+ conf = Path(args.conf)
277
+ try:
278
+ orig_lines = conf.read_text().splitlines(keepends=True)
279
+ except OSError:
280
+ orig_lines = []
281
+
282
+ lines = [comment]
283
+ if directory_base:
284
+ lines.append(f'directory "{directory_base}";')
285
+ lines.append("")
286
+
287
+ prev_end_pos = None
288
+ for name, file_path, line_no, block_text in zones:
289
+ block_end_line = line_no + block_text.count("\n")
290
+
291
+ if prev_end_pos is not None and orig_lines:
292
+ blank_count = 0
293
+ for i in range(prev_end_pos, block_end_line):
294
+ if i < len(orig_lines) and orig_lines[i].strip() == "":
295
+ blank_count += 1
296
+ for _ in range(blank_count):
297
+ lines.append("")
298
+
299
+ # Resolve relative file path against directory base for db_path substitution
300
+ is_relative = directory_base and not file_path.startswith("/")
301
+ resolve_path = str(PurePosixPath(directory_base) / file_path) if is_relative else file_path
302
+
303
+ # Apply db_path substitution on the resolved path
304
+ if args.db_path_find and args.db_path_replace:
305
+ resolve_path = resolve_path.replace(args.db_path_find, args.db_path_replace)
306
+
307
+ # If the substituted path still starts with the directory base, keep it relative
308
+ output_path = resolve_path
309
+ if is_relative:
310
+ try:
311
+ output_path = str(PurePosixPath(resolve_path).relative_to(directory_base))
312
+ except ValueError:
313
+ pass
314
+
315
+ transformed = _transform_zone_block(block_text, output_path, zone_types, target_type,
316
+ add_primaries=add_primaries,
317
+ primaries_content=args.primaries)
318
+ lines.append(transformed)
319
+ prev_end_pos = block_end_line
320
+
321
+ tmp = Path(args.out + ".new")
322
+ try:
323
+ tmp.write_text("\n".join(lines) + "\n")
324
+ tmp.replace(args.out)
325
+ logger.info(f"{len(zones)} zones written to {args.out}")
326
+ except OSError as e:
327
+ logger.error(f"Cannot write output file {args.out}: {e}")
328
+
329
+
330
+ def gen(args: argparse.Namespace) -> None:
331
+ """Generate a secondary-zone config from a primary-zone config."""
332
+ # Use default primaries for gen if not explicitly provided
333
+ if not args.primaries:
334
+ args.primaries = "10.0.0.100;"
335
+ _convert(args, ZONE_PRIMARY_TYPES, "secondary", add_primaries=True,
336
+ comment=args.comment)
337
+
338
+
339
+ def restore(args: argparse.Namespace) -> None:
340
+ """Convert a secondary-zone config back to a primary-zone config."""
341
+ _convert(args, ZONE_SECONDARY_TYPES, "primary", add_primaries=False,
342
+ comment=args.comment)
343
+
344
+
345
+ def convert(args: argparse.Namespace) -> None:
346
+ """Convert a folder of zone db files into a legacy named.conf for secondary zones.
347
+
348
+ Scans the directory given by --conf for db files, extracts the zone name from each
349
+ file's SOA record ($ORIGIN or SOA owner), and writes a legacy config with secondary
350
+ zone blocks to --out.
351
+ """
352
+ zone_dir = Path(args.conf)
353
+ if not zone_dir.is_dir():
354
+ logger.error(f"Zone directory {zone_dir} does not exist or is not a directory")
355
+ return
356
+
357
+ # Collect db files (non-recursive, skip hidden files)
358
+ db_files = sorted(
359
+ f for f in zone_dir.iterdir()
360
+ if f.is_file() and not f.name.startswith(".")
361
+ )
362
+
363
+ zones: list[tuple[str, str]] = [] # (zone_name, file_path)
364
+
365
+ for db_file in db_files:
366
+ zone_name = extract_zone_from_soa(str(db_file))
367
+ if zone_name is None:
368
+ logger.warning(f"Cannot extract zone name from {db_file.name}, skipping")
369
+ continue
370
+ # Exclude well-known local zones
371
+ if zone_name in EXCLUDE:
372
+ logger.debug(f"Skipping zone {zone_name}: excluded")
373
+ continue
374
+ zones.append((zone_name, str(db_file)))
375
+
376
+ if not zones:
377
+ logger.warning(f"No valid zone db files found in {zone_dir}")
378
+
379
+ is_secondary = bool(args.primaries)
380
+ lines = [args.comment]
381
+ for zone_name, file_path in zones:
382
+ lines.append(f'zone "{zone_name}" {{')
383
+ if is_secondary:
384
+ lines.append(" type secondary;")
385
+ lines.append(f' file "{file_path}";')
386
+ lines.append(f" primaries {{ {args.primaries} }};")
387
+ else:
388
+ lines.append(" type primary;")
389
+ lines.append(f' file "{file_path}";')
390
+ lines.append("};")
391
+ lines.append("")
392
+
393
+ tmp = Path(args.out + ".new")
394
+ try:
395
+ tmp.write_text("\n".join(lines) + "\n")
396
+ tmp.replace(args.out)
397
+ logger.info(f"{len(zones)} zones written to {args.out}")
398
+ except OSError as e:
399
+ logger.error(f"Cannot write output file {args.out}: {e}")
400
+
401
+
402
+ def catalog(args: argparse.Namespace) -> None:
403
+ """Build a catalog.zone zone list from a named.conf file.
404
+
405
+ Parses all zone blocks from the input config, computes SHA1 of each domain
406
+ name to use as the zone key, and writes a catalog.zone compatible config
407
+ to --out. Each zone line has the format:
408
+ <sha1> <domain>;
409
+
410
+ This is used by BIND's catalog.zone feature to define which zones should
411
+ be transferred between servers.
412
+ """
413
+ directory_base, zones = _parse_zones_from_file(args.conf, ZONE_PRIMARY_TYPES | ZONE_SECONDARY_TYPES)
414
+
415
+ # Deduplicate by domain name (lowercase, no trailing dot)
416
+ seen: dict[str, str] = {} # domain -> zone_name (original)
417
+ for name, file_path, line_no, block_text in zones:
418
+ domain = name.rstrip(".").lower()
419
+ if domain not in seen:
420
+ seen[domain] = name
421
+
422
+ if not seen:
423
+ logger.warning(f"No zones found in {args.conf}")
424
+ return
425
+
426
+ # Build catalog lines sorted by domain
427
+ lines = [args.comment]
428
+ for domain in sorted(seen.keys()):
429
+ sha1 = hashlib.sha1(domain.encode("utf-8")).hexdigest()
430
+ lines.append(f"{sha1} {domain};")
431
+
432
+ tmp = Path(args.out + ".new")
433
+ try:
434
+ tmp.write_text("\n".join(lines) + "\n")
435
+ tmp.replace(args.out)
436
+ logger.info(f"{len(seen)} zones written to {args.out}")
437
+ except OSError as e:
438
+ logger.error(f"Cannot write output file {args.out}: {e}")
439
+
440
+
441
+ def main() -> None:
442
+ args = parse_args()
443
+
444
+ # Configure logging with user-friendly format
445
+ level = getattr(logging, args.log_level.upper())
446
+ logging.basicConfig(
447
+ level=level,
448
+ format="%(asctime)s [%(levelname)-8s] %(message)s",
449
+ datefmt="%Y-%m-%d %H:%M:%S"
450
+ )
451
+
452
+ cmds = {"gen": gen, "restore": restore, "convert": convert, "catalog": catalog}
453
+ cmds[args.command](args)
454
+
455
+
456
+ if __name__ == "__main__":
457
+ main()
@@ -0,0 +1,354 @@
1
+ Metadata-Version: 2.4
2
+ Name: bind-zone-sync
3
+ Version: 0.2.1
4
+ Summary: Sync BIND zone configs between primary and secondary servers
5
+ Keywords: python,configuration,python-script,configuration-management,bind,named,bind9
6
+ Author: Lex SysKo
7
+ Author-email: Lex SysKo <lexsys.ko@gmail.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Operating System :: OS Independent
12
+ Requires-Python: >=3.12
13
+ Project-URL: Homepage, https://github.com/lexsysko/bind-zone-sync
14
+ Project-URL: Repository, https://github.com/lexsysko/bind-zone-sync.git
15
+ Project-URL: Issues, https://github.com/lexsysko/bind-zone-sync/issues
16
+ Description-Content-Type: text/markdown
17
+
18
+ # bind-zone-sync
19
+
20
+ Manage BIND zone configuration files: generate secondary-zone configs from primary-zone configs, restore primary configs from
21
+ secondary configs, and build legacy named.conf files from zone db file folders.
22
+
23
+ ## Features
24
+
25
+ - **`gen`** — Read a primary zone config and produce a secondary zone config, preserving the original multi-line formatting, blank
26
+ lines, indentation, and comments.
27
+ - **`restore`** — Convert a secondary zone config back to a primary zone config, removing the `primaries` directive and restoring
28
+ `type primary`.
29
+ - **`convert`** — Scan a folder of BIND zone db files, extract zone names from SOA records, and generate a legacy `named.conf`
30
+ with secondary zone blocks — useful for syncing zones when using BIND's `catalog.zone` feature.
31
+ - **`catalog`** — Parse a `named.conf` file, extract all zone domains, and produce a `catalog.zone` zone list where each
32
+ zone key is the SHA1 hash of its domain name — ready to include in BIND's `catalog` directive.
33
+ - **`directory` directive preservation** — If the input config uses a `directory` directive with relative file paths, the output
34
+ preserves the directive and keeps paths relative.
35
+ - **DB path substitution** — Automatically rewrite zone file paths (e.g., `primary/` → `secondary/`) during conversion.
36
+ - **Custom primaries content** — The `--primaries` option accepts any string for the `primaries` directive, supporting multiple
37
+ IPs, TSIG keys, or global settings.
38
+ - **Custom comment header** — The `--comment` option lets you set a custom comment line at the top of the output file.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install bind-zone-sync
44
+ # or
45
+ uv run bind-zone-sync --help
46
+ # or
47
+ uvx bind-zone-sync --help
48
+ ```
49
+
50
+ ### Standalone Usage (No Installation Required)
51
+
52
+ The `bind_zone_sync.py` script is self-contained and uses only Python standard library modules. You can copy it to any location
53
+ and run it directly without installing the package:
54
+
55
+ ```bash
56
+ # Download or copy the script
57
+ curl -o bind_zone_sync.py https://raw.githubusercontent.com/lexsysko/bind-zone-sync/main/src/bind_zone_sync/bind_zone_sync.py
58
+
59
+ # Run directly with Python
60
+ python bind_zone_sync.py gen --conf zones-primary.conf --out zones-secondary.conf
61
+ python bind_zone_sync.py restore --conf zones-secondary.conf --out zones-primary.conf
62
+ python bind_zone_sync.py convert --conf /path/to/zone-folder --out named.conf.legacy
63
+ python bind_zone_sync.py catalog --conf named.conf --out catalog.zone
64
+ ```
65
+
66
+ This is useful when you don't have pip/uv available or want a quick one-off conversion without setting up a Python environment.
67
+
68
+ ## Usage
69
+
70
+ ### Generate Secondary Config (`gen`)
71
+
72
+ Convert a primary zone config to a secondary zone config:
73
+
74
+ ```bash
75
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf
76
+ ```
77
+
78
+ Each zone block is transformed:
79
+
80
+ - `type primary` → `type secondary`
81
+ - `primaries { <address>; };` directive is added after the type line
82
+ - All other directives (allow-query, file, etc.) are preserved as-is
83
+ - Blank lines between zones match the original file
84
+
85
+ **With DB path substitution:**
86
+
87
+ ```bash
88
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
89
+ --db-path-find /usr/local/etc/namedb/primary/ \
90
+ --db-path-replace /usr/local/etc/namedb/secondary/
91
+ ```
92
+
93
+ This changes file paths like `/usr/local/etc/namedb/primary/app1.example.net.db` to
94
+ `/usr/local/etc/namedb/secondary/app1.example.net.db`.
95
+
96
+ **With custom primaries content:**
97
+
98
+ ```bash
99
+ # Single IP:
100
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
101
+ --primaries "10.0.0.100;"
102
+
103
+ # Multiple IPs:
104
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
105
+ --primaries "10.0.0.100; 10.0.0.101;"
106
+
107
+ # With TSIG key:
108
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
109
+ --primaries '10.0.0.100; key "mykey";'
110
+ ```
111
+
112
+ ### Restore Primary Config (`restore`)
113
+
114
+ Convert a secondary zone config back to a primary zone config:
115
+
116
+ ```bash
117
+ bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf
118
+ ```
119
+
120
+ Each zone block is transformed:
121
+
122
+ - `type secondary` → `type primary`
123
+ - `primaries { ... };` directive is removed
124
+ - All other directives are preserved as-is
125
+ - Blank lines between zones match the original file
126
+
127
+ **With DB path restoration:**
128
+
129
+ ```bash
130
+ bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf \
131
+ --db-path-find /usr/local/etc/namedb/secondary/ \
132
+ --db-path-replace /usr/local/etc/namedb/primary/
133
+ ```
134
+
135
+ ### Build Legacy Config from Zone DB Files (`convert`)
136
+
137
+ Scan a directory containing BIND zone db files and generate a legacy `named.conf`. The zone type depends on whether
138
+ `--primaries` is provided:
139
+
140
+ - **Without `--primaries`** — generates `type primary` zone blocks (for the primary/authoritative server).
141
+ - **With `--primaries`** — generates `type secondary` zone blocks with the `primaries` directive (for secondary servers,
142
+ useful when using BIND's `catalog.zone` feature).
143
+
144
+ **Generate primary zones (default):**
145
+
146
+ ```bash
147
+ bind-zone-sync convert --conf /path/to/zone-folder --out /usr/local/etc/namedb/named.conf.zones
148
+ ```
149
+
150
+ Output:
151
+
152
+ ```
153
+ zone "app1.example.net" {
154
+ type primary;
155
+ file "/path/to/zone-folder/db.app1.example.net";
156
+ };
157
+ ```
158
+
159
+ **Generate secondary zones (with `--primaries`):**
160
+
161
+ ```bash
162
+ bind-zone-sync convert --conf /path/to/zone-folder --out /usr/local/etc/namedb/named.conf.legacy-zones \
163
+ --primaries "10.0.0.100;"
164
+ ```
165
+
166
+ Output:
167
+
168
+ ```
169
+ zone "app1.example.net" {
170
+ type secondary;
171
+ file "/path/to/zone-folder/db.app1.example.net";
172
+ primaries { 10.0.0.100; };
173
+ };
174
+ ```
175
+
176
+ **With custom comment header:**
177
+
178
+ ```bash
179
+ bind-zone-sync convert --conf /path/to/zone-folder --out named.conf.legacy \
180
+ --comment "// legacy zones for secondary sync"
181
+ ```
182
+
183
+ The `convert` command:
184
+
185
+ - Scans the directory non-recursively, skipping hidden files (starting with `.`)
186
+ - Extracts zone names from `$ORIGIN` directives or SOA owner names
187
+ - Excludes well-known local zones (localhost, loopback, etc.)
188
+ - Writes `type primary` by default, or `type secondary` with `primaries` when `--primaries` is set
189
+
190
+ ### Build Catalog Zone List (`catalog`)
191
+
192
+ Parse a `named.conf` file, extract all zone domains, and produce a `catalog.zone` zone list where each zone key is the
193
+ SHA1 hash of its domain name. This output is ready to include in BIND's `catalog` directive for automatic zone
194
+ synchronization between servers.
195
+
196
+ ```bash
197
+ bind-zone-sync catalog --conf /usr/local/etc/namedb/named.conf --out /usr/local/etc/namedb/catalog.zone
198
+ ```
199
+
200
+ Output:
201
+
202
+ ```
203
+ // generated by bind-zone-sync, do not edit
204
+ a1b2c3d4e5f6789012345678901234567890abcd app1.example.net;
205
+ b2c3d4e5f6789012345678901234567890abcde app2.example.net;
206
+ ```
207
+
208
+ Each line contains a SHA1 hash (the zone key) followed by the domain name. BIND uses these keys in its `catalog.zone`
209
+ feature to track and synchronize zones across servers.
210
+
211
+ The `catalog` command:
212
+
213
+ - Parses both `type primary` and `type secondary` zone blocks from the input config
214
+ - Excludes well-known local zones (localhost, loopback, etc.)
215
+ - Deduplicates zones by domain name
216
+ - Sorts output alphabetically by domain name
217
+ - Computes SHA1 hash of each domain name as the zone key
218
+
219
+ ## Command-Line Options
220
+
221
+ | Option | Default | Description |
222
+ |---------------------|---------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|
223
+ | `--conf` | `/usr/local/etc/namedb/zones-primary.conf.auto` | Input zone config file (for `gen`/`restore`/`catalog`) or zone db files directory (for `convert`) |
224
+ | `--out` | `/usr/local/etc/namedb/zones-secondary.conf.auto` | Output zone config file |
225
+ | `--primaries` | `""` (empty) | When set, generates secondary zones with the `primaries` directive; when omitted, generates primary zones (e.g., `"10.0.0.100;"`) |
226
+ | `--db-path-find` | `/usr/local/etc/namedb/primary/` | Path prefix in zone file paths to replace |
227
+ | `--db-path-replace` | `""` | Replacement path prefix; empty = keep original paths |
228
+ | `--comment` | `// generated by bind-zone-sync, do not edit` | Comment header line in the output file |
229
+ | `--log-level` | `INFO` | Logging level: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` |
230
+
231
+ ## Excluded Zones
232
+
233
+ The following zones are automatically excluded from replication (they stay local on every server):
234
+
235
+ - `localhost`
236
+ - `0.0.127.in-addr.arpa`
237
+ - `127.in-addr.arpa`
238
+ - `255.in-addr.arpa`
239
+ - `0.in-addr.arpa`
240
+ - IPv6 loopback reverse zone
241
+
242
+ ## Output Format
243
+
244
+ Both `gen` and `restore` preserve the original config file's formatting:
245
+
246
+ - **Multi-line zone blocks** — Each zone keeps its original indentation and line structure
247
+ - **Blank lines** — Blank lines between zone blocks are preserved from the original file
248
+ - **Comments** — Inline comments within zone blocks are kept
249
+ - **Directives** — All directives other than `type` and `primaries` are unchanged
250
+ - **`directory` directive** — If present in the input, it is copied to the output and file paths remain relative
251
+
252
+ ### Directory Directive Example
253
+
254
+ **Primary input (with `directory`):**
255
+
256
+ ```
257
+ directory "/usr/local/etc/namedb/zones";
258
+
259
+ zone "app1.example.net" {
260
+ type primary;
261
+ file "app1.example.net.db";
262
+ };
263
+ ```
264
+
265
+ **Secondary output (`gen`):**
266
+
267
+ ```
268
+ directory "/usr/local/etc/namedb/zones";
269
+
270
+ zone "app1.example.net" {
271
+ type secondary;
272
+ primaries { 10.0.0.100; };
273
+ file "app1.example.net.db";
274
+ };
275
+ ```
276
+
277
+ The `directory` directive is preserved, and the relative file path `"app1.example.net.db"` stays relative instead of being
278
+ expanded to an absolute path.
279
+
280
+ ### Example
281
+
282
+ **Primary input:**
283
+
284
+ ```
285
+ zone "app1.example.net" {
286
+ type primary;
287
+ allow-query { any; };
288
+ file "/usr/local/etc/namedb/primary/db.app1.example.net";
289
+ };
290
+ ```
291
+
292
+ **Secondary output (`gen`):**
293
+
294
+ ```
295
+ zone "app1.example.net" {
296
+ type secondary;
297
+ primaries { 10.0.0.100; };
298
+ allow-query { any; };
299
+ file "/usr/local/etc/namedb/secondary/db.app1.example.net";
300
+ };
301
+ ```
302
+
303
+ ## Examples
304
+
305
+ ### Test without BIND installed
306
+
307
+ ```bash
308
+ # Generate secondary config from primary
309
+ uv run bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf
310
+
311
+ # Restore primary config from secondary
312
+ uv run bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf
313
+ ```
314
+
315
+ ### Full production workflow
316
+
317
+ ```bash
318
+ # On the primary server: generate the secondary config
319
+ bind-zone-sync gen --conf /usr/local/etc/namedb/zones-primary.conf \
320
+ --out /usr/local/etc/namedb/zones-secondary.conf \
321
+ --primaries "10.0.0.100;" \
322
+ --db-path-find /usr/local/etc/namedb/primary/ \
323
+ --db-path-replace /usr/local/etc/namedb/secondary/
324
+
325
+ # Deploy zones-secondary.conf to the secondary server
326
+
327
+ # If you need to restore a primary config from a secondary backup
328
+ bind-zone-sync restore --conf /usr/local/etc/namedb/zones-secondary.conf \
329
+ --out /usr/local/etc/namedb/zones-primary.conf \
330
+ --db-path-find /usr/local/etc/namedb/secondary/ \
331
+ --db-path-replace /usr/local/etc/namedb/primary/
332
+ ```
333
+
334
+ ### Legacy zones sync with catalog.zone
335
+
336
+ ```bash
337
+ # On the primary server — build zone config with type primary
338
+ bind-zone-sync convert --conf /usr/local/etc/namedb/zones/ \
339
+ --out /usr/local/etc/namedb/named.conf.zones
340
+
341
+ # On the secondary server — build zone config with type secondary
342
+ bind-zone-sync convert --conf /usr/local/etc/namedb/zones/ \
343
+ --out /usr/local/etc/namedb/named.conf.legacy-zones \
344
+ --primaries "10.0.0.100;"
345
+
346
+ # Build a catalog.zone zone list from named.conf (SHA1 keys)
347
+ bind-zone-sync catalog --conf /usr/local/etc/namedb/named.conf \
348
+ --out /usr/local/etc/namedb/catalog.zone
349
+
350
+ # Include the generated config in your main named.conf
351
+ # include "/usr/local/etc/namedb/named.conf.zones";
352
+ # include "/usr/local/etc/namedb/named.conf.legacy-zones";
353
+ # catalog "catalog.zone" { zones "/usr/local/etc/namedb/catalog.zone"; };
354
+ ```
@@ -0,0 +1,7 @@
1
+ bind_zone_sync/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ bind_zone_sync/bind_zone_sync.py,sha256=SBIDw_vSQlEJHIS2lR6u5g_V5BtTMYBsJ5m79QGZRZk,17953
3
+ bind_zone_sync-0.2.1.dist-info/licenses/LICENSE,sha256=RG34pGHwN44tfFlPVQhjTzbAf1Hu1dBUrSU-v_PVvw8,1066
4
+ bind_zone_sync-0.2.1.dist-info/WHEEL,sha256=1dD_GoEqEIxQ7VnrUExgdj_eExY4b4UgfR0iBlGKVac,80
5
+ bind_zone_sync-0.2.1.dist-info/entry_points.txt,sha256=hYEP32r9-JxFitvncq7VAs39xv8jIKvr8lSc6VT5Ih8,71
6
+ bind_zone_sync-0.2.1.dist-info/METADATA,sha256=Hatp4vO6Ld1ReU01C9mJNLxI2q74yhs18HfG3g1NQOM,13347
7
+ bind_zone_sync-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ bind-zone-sync = bind_zone_sync.bind_zone_sync:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lex SysKo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.