bind-zone-sync 0.2.0__tar.gz

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.

Potentially problematic release.


This version of bind-zone-sync might be problematic. Click here for more details.

@@ -0,0 +1,346 @@
1
+ Metadata-Version: 2.3
2
+ Name: bind-zone-sync
3
+ Version: 0.2.0
4
+ Summary: Sync BIND zone configs between primary and secondary servers
5
+ Author: Lex SysKo
6
+ Author-email: Lex SysKo <lexsys.ko@gmail.com>
7
+ Requires-Python: >=3.12
8
+ Description-Content-Type: text/markdown
9
+
10
+ # bind-zone-sync
11
+
12
+ Manage BIND zone configuration files: generate secondary-zone configs from primary-zone configs, restore primary configs from
13
+ secondary configs, and build legacy named.conf files from zone db file folders.
14
+
15
+ ## Features
16
+
17
+ - **`gen`** — Read a primary zone config and produce a secondary zone config, preserving the original multi-line formatting, blank
18
+ lines, indentation, and comments.
19
+ - **`restore`** — Convert a secondary zone config back to a primary zone config, removing the `primaries` directive and restoring
20
+ `type primary`.
21
+ - **`convert`** — Scan a folder of BIND zone db files, extract zone names from SOA records, and generate a legacy `named.conf`
22
+ with secondary zone blocks — useful for syncing zones when using BIND's `catalog.zone` feature.
23
+ - **`catalog`** — Parse a `named.conf` file, extract all zone domains, and produce a `catalog.zone` zone list where each
24
+ zone key is the SHA1 hash of its domain name — ready to include in BIND's `catalog` directive.
25
+ - **`directory` directive preservation** — If the input config uses a `directory` directive with relative file paths, the output
26
+ preserves the directive and keeps paths relative.
27
+ - **DB path substitution** — Automatically rewrite zone file paths (e.g., `primary/` → `secondary/`) during conversion.
28
+ - **Custom primaries content** — The `--primaries` option accepts any string for the `primaries` directive, supporting multiple
29
+ IPs, TSIG keys, or global settings.
30
+ - **Custom comment header** — The `--comment` option lets you set a custom comment line at the top of the output file.
31
+
32
+ ## Installation
33
+
34
+ ```bash
35
+ pip install bind-zone-sync
36
+ # or
37
+ uv run bind-zone-sync --help
38
+ # or
39
+ uvx bind-zone-sync --help
40
+ ```
41
+
42
+ ### Standalone Usage (No Installation Required)
43
+
44
+ The `bind_zone_sync.py` script is self-contained and uses only Python standard library modules. You can copy it to any location
45
+ and run it directly without installing the package:
46
+
47
+ ```bash
48
+ # Download or copy the script
49
+ curl -o bind_zone_sync.py https://raw.githubusercontent.com/lexsysko/bind-zone-sync/main/src/bind_zone_sync/bind_zone_sync.py
50
+
51
+ # Run directly with Python
52
+ python bind_zone_sync.py gen --conf zones-primary.conf --out zones-secondary.conf
53
+ python bind_zone_sync.py restore --conf zones-secondary.conf --out zones-primary.conf
54
+ python bind_zone_sync.py convert --conf /path/to/zone-folder --out named.conf.legacy
55
+ python bind_zone_sync.py catalog --conf named.conf --out catalog.zone
56
+ ```
57
+
58
+ This is useful when you don't have pip/uv available or want a quick one-off conversion without setting up a Python environment.
59
+
60
+ ## Usage
61
+
62
+ ### Generate Secondary Config (`gen`)
63
+
64
+ Convert a primary zone config to a secondary zone config:
65
+
66
+ ```bash
67
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf
68
+ ```
69
+
70
+ Each zone block is transformed:
71
+
72
+ - `type primary` → `type secondary`
73
+ - `primaries { <address>; };` directive is added after the type line
74
+ - All other directives (allow-query, file, etc.) are preserved as-is
75
+ - Blank lines between zones match the original file
76
+
77
+ **With DB path substitution:**
78
+
79
+ ```bash
80
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
81
+ --db-path-find /usr/local/etc/namedb/primary/ \
82
+ --db-path-replace /usr/local/etc/namedb/secondary/
83
+ ```
84
+
85
+ This changes file paths like `/usr/local/etc/namedb/primary/app1.example.net.db` to
86
+ `/usr/local/etc/namedb/secondary/app1.example.net.db`.
87
+
88
+ **With custom primaries content:**
89
+
90
+ ```bash
91
+ # Single IP:
92
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
93
+ --primaries "10.0.0.100;"
94
+
95
+ # Multiple IPs:
96
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
97
+ --primaries "10.0.0.100; 10.0.0.101;"
98
+
99
+ # With TSIG key:
100
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
101
+ --primaries '10.0.0.100; key "mykey";'
102
+ ```
103
+
104
+ ### Restore Primary Config (`restore`)
105
+
106
+ Convert a secondary zone config back to a primary zone config:
107
+
108
+ ```bash
109
+ bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf
110
+ ```
111
+
112
+ Each zone block is transformed:
113
+
114
+ - `type secondary` → `type primary`
115
+ - `primaries { ... };` directive is removed
116
+ - All other directives are preserved as-is
117
+ - Blank lines between zones match the original file
118
+
119
+ **With DB path restoration:**
120
+
121
+ ```bash
122
+ bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf \
123
+ --db-path-find /usr/local/etc/namedb/secondary/ \
124
+ --db-path-replace /usr/local/etc/namedb/primary/
125
+ ```
126
+
127
+ ### Build Legacy Config from Zone DB Files (`convert`)
128
+
129
+ Scan a directory containing BIND zone db files and generate a legacy `named.conf`. The zone type depends on whether
130
+ `--primaries` is provided:
131
+
132
+ - **Without `--primaries`** — generates `type primary` zone blocks (for the primary/authoritative server).
133
+ - **With `--primaries`** — generates `type secondary` zone blocks with the `primaries` directive (for secondary servers,
134
+ useful when using BIND's `catalog.zone` feature).
135
+
136
+ **Generate primary zones (default):**
137
+
138
+ ```bash
139
+ bind-zone-sync convert --conf /path/to/zone-folder --out /usr/local/etc/namedb/named.conf.zones
140
+ ```
141
+
142
+ Output:
143
+
144
+ ```
145
+ zone "app1.example.net" {
146
+ type primary;
147
+ file "/path/to/zone-folder/db.app1.example.net";
148
+ };
149
+ ```
150
+
151
+ **Generate secondary zones (with `--primaries`):**
152
+
153
+ ```bash
154
+ bind-zone-sync convert --conf /path/to/zone-folder --out /usr/local/etc/namedb/named.conf.legacy-zones \
155
+ --primaries "10.0.0.100;"
156
+ ```
157
+
158
+ Output:
159
+
160
+ ```
161
+ zone "app1.example.net" {
162
+ type secondary;
163
+ file "/path/to/zone-folder/db.app1.example.net";
164
+ primaries { 10.0.0.100; };
165
+ };
166
+ ```
167
+
168
+ **With custom comment header:**
169
+
170
+ ```bash
171
+ bind-zone-sync convert --conf /path/to/zone-folder --out named.conf.legacy \
172
+ --comment "// legacy zones for secondary sync"
173
+ ```
174
+
175
+ The `convert` command:
176
+
177
+ - Scans the directory non-recursively, skipping hidden files (starting with `.`)
178
+ - Extracts zone names from `$ORIGIN` directives or SOA owner names
179
+ - Excludes well-known local zones (localhost, loopback, etc.)
180
+ - Writes `type primary` by default, or `type secondary` with `primaries` when `--primaries` is set
181
+
182
+ ### Build Catalog Zone List (`catalog`)
183
+
184
+ Parse a `named.conf` file, extract all zone domains, and produce a `catalog.zone` zone list where each zone key is the
185
+ SHA1 hash of its domain name. This output is ready to include in BIND's `catalog` directive for automatic zone
186
+ synchronization between servers.
187
+
188
+ ```bash
189
+ bind-zone-sync catalog --conf /usr/local/etc/namedb/named.conf --out /usr/local/etc/namedb/catalog.zone
190
+ ```
191
+
192
+ Output:
193
+
194
+ ```
195
+ // generated by bind-zone-sync, do not edit
196
+ a1b2c3d4e5f6789012345678901234567890abcd app1.example.net;
197
+ b2c3d4e5f6789012345678901234567890abcde app2.example.net;
198
+ ```
199
+
200
+ Each line contains a SHA1 hash (the zone key) followed by the domain name. BIND uses these keys in its `catalog.zone`
201
+ feature to track and synchronize zones across servers.
202
+
203
+ The `catalog` command:
204
+
205
+ - Parses both `type primary` and `type secondary` zone blocks from the input config
206
+ - Excludes well-known local zones (localhost, loopback, etc.)
207
+ - Deduplicates zones by domain name
208
+ - Sorts output alphabetically by domain name
209
+ - Computes SHA1 hash of each domain name as the zone key
210
+
211
+ ## Command-Line Options
212
+
213
+ | Option | Default | Description |
214
+ |---------------------|---------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|
215
+ | `--conf` | `/usr/local/etc/namedb/zones-primary.conf.auto` | Input zone config file (for `gen`/`restore`/`catalog`) or zone db files directory (for `convert`) |
216
+ | `--out` | `/usr/local/etc/namedb/zones-secondary.conf.auto` | Output zone config file |
217
+ | `--primaries` | `""` (empty) | When set, generates secondary zones with the `primaries` directive; when omitted, generates primary zones (e.g., `"10.0.0.100;"`) |
218
+ | `--db-path-find` | `/usr/local/etc/namedb/primary/` | Path prefix in zone file paths to replace |
219
+ | `--db-path-replace` | `""` | Replacement path prefix; empty = keep original paths |
220
+ | `--comment` | `// generated by bind-zone-sync, do not edit` | Comment header line in the output file |
221
+ | `--log-level` | `INFO` | Logging level: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` |
222
+
223
+ ## Excluded Zones
224
+
225
+ The following zones are automatically excluded from replication (they stay local on every server):
226
+
227
+ - `localhost`
228
+ - `0.0.127.in-addr.arpa`
229
+ - `127.in-addr.arpa`
230
+ - `255.in-addr.arpa`
231
+ - `0.in-addr.arpa`
232
+ - IPv6 loopback reverse zone
233
+
234
+ ## Output Format
235
+
236
+ Both `gen` and `restore` preserve the original config file's formatting:
237
+
238
+ - **Multi-line zone blocks** — Each zone keeps its original indentation and line structure
239
+ - **Blank lines** — Blank lines between zone blocks are preserved from the original file
240
+ - **Comments** — Inline comments within zone blocks are kept
241
+ - **Directives** — All directives other than `type` and `primaries` are unchanged
242
+ - **`directory` directive** — If present in the input, it is copied to the output and file paths remain relative
243
+
244
+ ### Directory Directive Example
245
+
246
+ **Primary input (with `directory`):**
247
+
248
+ ```
249
+ directory "/usr/local/etc/namedb/zones";
250
+
251
+ zone "app1.example.net" {
252
+ type primary;
253
+ file "app1.example.net.db";
254
+ };
255
+ ```
256
+
257
+ **Secondary output (`gen`):**
258
+
259
+ ```
260
+ directory "/usr/local/etc/namedb/zones";
261
+
262
+ zone "app1.example.net" {
263
+ type secondary;
264
+ primaries { 10.0.0.100; };
265
+ file "app1.example.net.db";
266
+ };
267
+ ```
268
+
269
+ The `directory` directive is preserved, and the relative file path `"app1.example.net.db"` stays relative instead of being
270
+ expanded to an absolute path.
271
+
272
+ ### Example
273
+
274
+ **Primary input:**
275
+
276
+ ```
277
+ zone "app1.example.net" {
278
+ type primary;
279
+ allow-query { any; };
280
+ file "/usr/local/etc/namedb/primary/db.app1.example.net";
281
+ };
282
+ ```
283
+
284
+ **Secondary output (`gen`):**
285
+
286
+ ```
287
+ zone "app1.example.net" {
288
+ type secondary;
289
+ primaries { 10.0.0.100; };
290
+ allow-query { any; };
291
+ file "/usr/local/etc/namedb/secondary/db.app1.example.net";
292
+ };
293
+ ```
294
+
295
+ ## Examples
296
+
297
+ ### Test without BIND installed
298
+
299
+ ```bash
300
+ # Generate secondary config from primary
301
+ uv run bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf
302
+
303
+ # Restore primary config from secondary
304
+ uv run bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf
305
+ ```
306
+
307
+ ### Full production workflow
308
+
309
+ ```bash
310
+ # On the primary server: generate the secondary config
311
+ bind-zone-sync gen --conf /usr/local/etc/namedb/zones-primary.conf \
312
+ --out /usr/local/etc/namedb/zones-secondary.conf \
313
+ --primaries "10.0.0.100;" \
314
+ --db-path-find /usr/local/etc/namedb/primary/ \
315
+ --db-path-replace /usr/local/etc/namedb/secondary/
316
+
317
+ # Deploy zones-secondary.conf to the secondary server
318
+
319
+ # If you need to restore a primary config from a secondary backup
320
+ bind-zone-sync restore --conf /usr/local/etc/namedb/zones-secondary.conf \
321
+ --out /usr/local/etc/namedb/zones-primary.conf \
322
+ --db-path-find /usr/local/etc/namedb/secondary/ \
323
+ --db-path-replace /usr/local/etc/namedb/primary/
324
+ ```
325
+
326
+ ### Legacy zones sync with catalog.zone
327
+
328
+ ```bash
329
+ # On the primary server — build zone config with type primary
330
+ bind-zone-sync convert --conf /usr/local/etc/namedb/zones/ \
331
+ --out /usr/local/etc/namedb/named.conf.zones
332
+
333
+ # On the secondary server — build zone config with type secondary
334
+ bind-zone-sync convert --conf /usr/local/etc/namedb/zones/ \
335
+ --out /usr/local/etc/namedb/named.conf.legacy-zones \
336
+ --primaries "10.0.0.100;"
337
+
338
+ # Build a catalog.zone zone list from named.conf (SHA1 keys)
339
+ bind-zone-sync catalog --conf /usr/local/etc/namedb/named.conf \
340
+ --out /usr/local/etc/namedb/catalog.zone
341
+
342
+ # Include the generated config in your main named.conf
343
+ # include "/usr/local/etc/namedb/named.conf.zones";
344
+ # include "/usr/local/etc/namedb/named.conf.legacy-zones";
345
+ # catalog "catalog.zone" { zones "/usr/local/etc/namedb/catalog.zone"; };
346
+ ```
@@ -0,0 +1,337 @@
1
+ # bind-zone-sync
2
+
3
+ Manage BIND zone configuration files: generate secondary-zone configs from primary-zone configs, restore primary configs from
4
+ secondary configs, and build legacy named.conf files from zone db file folders.
5
+
6
+ ## Features
7
+
8
+ - **`gen`** — Read a primary zone config and produce a secondary zone config, preserving the original multi-line formatting, blank
9
+ lines, indentation, and comments.
10
+ - **`restore`** — Convert a secondary zone config back to a primary zone config, removing the `primaries` directive and restoring
11
+ `type primary`.
12
+ - **`convert`** — Scan a folder of BIND zone db files, extract zone names from SOA records, and generate a legacy `named.conf`
13
+ with secondary zone blocks — useful for syncing zones when using BIND's `catalog.zone` feature.
14
+ - **`catalog`** — Parse a `named.conf` file, extract all zone domains, and produce a `catalog.zone` zone list where each
15
+ zone key is the SHA1 hash of its domain name — ready to include in BIND's `catalog` directive.
16
+ - **`directory` directive preservation** — If the input config uses a `directory` directive with relative file paths, the output
17
+ preserves the directive and keeps paths relative.
18
+ - **DB path substitution** — Automatically rewrite zone file paths (e.g., `primary/` → `secondary/`) during conversion.
19
+ - **Custom primaries content** — The `--primaries` option accepts any string for the `primaries` directive, supporting multiple
20
+ IPs, TSIG keys, or global settings.
21
+ - **Custom comment header** — The `--comment` option lets you set a custom comment line at the top of the output file.
22
+
23
+ ## Installation
24
+
25
+ ```bash
26
+ pip install bind-zone-sync
27
+ # or
28
+ uv run bind-zone-sync --help
29
+ # or
30
+ uvx bind-zone-sync --help
31
+ ```
32
+
33
+ ### Standalone Usage (No Installation Required)
34
+
35
+ The `bind_zone_sync.py` script is self-contained and uses only Python standard library modules. You can copy it to any location
36
+ and run it directly without installing the package:
37
+
38
+ ```bash
39
+ # Download or copy the script
40
+ curl -o bind_zone_sync.py https://raw.githubusercontent.com/lexsysko/bind-zone-sync/main/src/bind_zone_sync/bind_zone_sync.py
41
+
42
+ # Run directly with Python
43
+ python bind_zone_sync.py gen --conf zones-primary.conf --out zones-secondary.conf
44
+ python bind_zone_sync.py restore --conf zones-secondary.conf --out zones-primary.conf
45
+ python bind_zone_sync.py convert --conf /path/to/zone-folder --out named.conf.legacy
46
+ python bind_zone_sync.py catalog --conf named.conf --out catalog.zone
47
+ ```
48
+
49
+ This is useful when you don't have pip/uv available or want a quick one-off conversion without setting up a Python environment.
50
+
51
+ ## Usage
52
+
53
+ ### Generate Secondary Config (`gen`)
54
+
55
+ Convert a primary zone config to a secondary zone config:
56
+
57
+ ```bash
58
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf
59
+ ```
60
+
61
+ Each zone block is transformed:
62
+
63
+ - `type primary` → `type secondary`
64
+ - `primaries { <address>; };` directive is added after the type line
65
+ - All other directives (allow-query, file, etc.) are preserved as-is
66
+ - Blank lines between zones match the original file
67
+
68
+ **With DB path substitution:**
69
+
70
+ ```bash
71
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
72
+ --db-path-find /usr/local/etc/namedb/primary/ \
73
+ --db-path-replace /usr/local/etc/namedb/secondary/
74
+ ```
75
+
76
+ This changes file paths like `/usr/local/etc/namedb/primary/app1.example.net.db` to
77
+ `/usr/local/etc/namedb/secondary/app1.example.net.db`.
78
+
79
+ **With custom primaries content:**
80
+
81
+ ```bash
82
+ # Single IP:
83
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
84
+ --primaries "10.0.0.100;"
85
+
86
+ # Multiple IPs:
87
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
88
+ --primaries "10.0.0.100; 10.0.0.101;"
89
+
90
+ # With TSIG key:
91
+ bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf \
92
+ --primaries '10.0.0.100; key "mykey";'
93
+ ```
94
+
95
+ ### Restore Primary Config (`restore`)
96
+
97
+ Convert a secondary zone config back to a primary zone config:
98
+
99
+ ```bash
100
+ bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf
101
+ ```
102
+
103
+ Each zone block is transformed:
104
+
105
+ - `type secondary` → `type primary`
106
+ - `primaries { ... };` directive is removed
107
+ - All other directives are preserved as-is
108
+ - Blank lines between zones match the original file
109
+
110
+ **With DB path restoration:**
111
+
112
+ ```bash
113
+ bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf \
114
+ --db-path-find /usr/local/etc/namedb/secondary/ \
115
+ --db-path-replace /usr/local/etc/namedb/primary/
116
+ ```
117
+
118
+ ### Build Legacy Config from Zone DB Files (`convert`)
119
+
120
+ Scan a directory containing BIND zone db files and generate a legacy `named.conf`. The zone type depends on whether
121
+ `--primaries` is provided:
122
+
123
+ - **Without `--primaries`** — generates `type primary` zone blocks (for the primary/authoritative server).
124
+ - **With `--primaries`** — generates `type secondary` zone blocks with the `primaries` directive (for secondary servers,
125
+ useful when using BIND's `catalog.zone` feature).
126
+
127
+ **Generate primary zones (default):**
128
+
129
+ ```bash
130
+ bind-zone-sync convert --conf /path/to/zone-folder --out /usr/local/etc/namedb/named.conf.zones
131
+ ```
132
+
133
+ Output:
134
+
135
+ ```
136
+ zone "app1.example.net" {
137
+ type primary;
138
+ file "/path/to/zone-folder/db.app1.example.net";
139
+ };
140
+ ```
141
+
142
+ **Generate secondary zones (with `--primaries`):**
143
+
144
+ ```bash
145
+ bind-zone-sync convert --conf /path/to/zone-folder --out /usr/local/etc/namedb/named.conf.legacy-zones \
146
+ --primaries "10.0.0.100;"
147
+ ```
148
+
149
+ Output:
150
+
151
+ ```
152
+ zone "app1.example.net" {
153
+ type secondary;
154
+ file "/path/to/zone-folder/db.app1.example.net";
155
+ primaries { 10.0.0.100; };
156
+ };
157
+ ```
158
+
159
+ **With custom comment header:**
160
+
161
+ ```bash
162
+ bind-zone-sync convert --conf /path/to/zone-folder --out named.conf.legacy \
163
+ --comment "// legacy zones for secondary sync"
164
+ ```
165
+
166
+ The `convert` command:
167
+
168
+ - Scans the directory non-recursively, skipping hidden files (starting with `.`)
169
+ - Extracts zone names from `$ORIGIN` directives or SOA owner names
170
+ - Excludes well-known local zones (localhost, loopback, etc.)
171
+ - Writes `type primary` by default, or `type secondary` with `primaries` when `--primaries` is set
172
+
173
+ ### Build Catalog Zone List (`catalog`)
174
+
175
+ Parse a `named.conf` file, extract all zone domains, and produce a `catalog.zone` zone list where each zone key is the
176
+ SHA1 hash of its domain name. This output is ready to include in BIND's `catalog` directive for automatic zone
177
+ synchronization between servers.
178
+
179
+ ```bash
180
+ bind-zone-sync catalog --conf /usr/local/etc/namedb/named.conf --out /usr/local/etc/namedb/catalog.zone
181
+ ```
182
+
183
+ Output:
184
+
185
+ ```
186
+ // generated by bind-zone-sync, do not edit
187
+ a1b2c3d4e5f6789012345678901234567890abcd app1.example.net;
188
+ b2c3d4e5f6789012345678901234567890abcde app2.example.net;
189
+ ```
190
+
191
+ Each line contains a SHA1 hash (the zone key) followed by the domain name. BIND uses these keys in its `catalog.zone`
192
+ feature to track and synchronize zones across servers.
193
+
194
+ The `catalog` command:
195
+
196
+ - Parses both `type primary` and `type secondary` zone blocks from the input config
197
+ - Excludes well-known local zones (localhost, loopback, etc.)
198
+ - Deduplicates zones by domain name
199
+ - Sorts output alphabetically by domain name
200
+ - Computes SHA1 hash of each domain name as the zone key
201
+
202
+ ## Command-Line Options
203
+
204
+ | Option | Default | Description |
205
+ |---------------------|---------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------|
206
+ | `--conf` | `/usr/local/etc/namedb/zones-primary.conf.auto` | Input zone config file (for `gen`/`restore`/`catalog`) or zone db files directory (for `convert`) |
207
+ | `--out` | `/usr/local/etc/namedb/zones-secondary.conf.auto` | Output zone config file |
208
+ | `--primaries` | `""` (empty) | When set, generates secondary zones with the `primaries` directive; when omitted, generates primary zones (e.g., `"10.0.0.100;"`) |
209
+ | `--db-path-find` | `/usr/local/etc/namedb/primary/` | Path prefix in zone file paths to replace |
210
+ | `--db-path-replace` | `""` | Replacement path prefix; empty = keep original paths |
211
+ | `--comment` | `// generated by bind-zone-sync, do not edit` | Comment header line in the output file |
212
+ | `--log-level` | `INFO` | Logging level: `DEBUG`, `INFO`, `WARNING`, `ERROR`, `CRITICAL` |
213
+
214
+ ## Excluded Zones
215
+
216
+ The following zones are automatically excluded from replication (they stay local on every server):
217
+
218
+ - `localhost`
219
+ - `0.0.127.in-addr.arpa`
220
+ - `127.in-addr.arpa`
221
+ - `255.in-addr.arpa`
222
+ - `0.in-addr.arpa`
223
+ - IPv6 loopback reverse zone
224
+
225
+ ## Output Format
226
+
227
+ Both `gen` and `restore` preserve the original config file's formatting:
228
+
229
+ - **Multi-line zone blocks** — Each zone keeps its original indentation and line structure
230
+ - **Blank lines** — Blank lines between zone blocks are preserved from the original file
231
+ - **Comments** — Inline comments within zone blocks are kept
232
+ - **Directives** — All directives other than `type` and `primaries` are unchanged
233
+ - **`directory` directive** — If present in the input, it is copied to the output and file paths remain relative
234
+
235
+ ### Directory Directive Example
236
+
237
+ **Primary input (with `directory`):**
238
+
239
+ ```
240
+ directory "/usr/local/etc/namedb/zones";
241
+
242
+ zone "app1.example.net" {
243
+ type primary;
244
+ file "app1.example.net.db";
245
+ };
246
+ ```
247
+
248
+ **Secondary output (`gen`):**
249
+
250
+ ```
251
+ directory "/usr/local/etc/namedb/zones";
252
+
253
+ zone "app1.example.net" {
254
+ type secondary;
255
+ primaries { 10.0.0.100; };
256
+ file "app1.example.net.db";
257
+ };
258
+ ```
259
+
260
+ The `directory` directive is preserved, and the relative file path `"app1.example.net.db"` stays relative instead of being
261
+ expanded to an absolute path.
262
+
263
+ ### Example
264
+
265
+ **Primary input:**
266
+
267
+ ```
268
+ zone "app1.example.net" {
269
+ type primary;
270
+ allow-query { any; };
271
+ file "/usr/local/etc/namedb/primary/db.app1.example.net";
272
+ };
273
+ ```
274
+
275
+ **Secondary output (`gen`):**
276
+
277
+ ```
278
+ zone "app1.example.net" {
279
+ type secondary;
280
+ primaries { 10.0.0.100; };
281
+ allow-query { any; };
282
+ file "/usr/local/etc/namedb/secondary/db.app1.example.net";
283
+ };
284
+ ```
285
+
286
+ ## Examples
287
+
288
+ ### Test without BIND installed
289
+
290
+ ```bash
291
+ # Generate secondary config from primary
292
+ uv run bind-zone-sync gen --conf zones-primary.conf --out zones-secondary.conf
293
+
294
+ # Restore primary config from secondary
295
+ uv run bind-zone-sync restore --conf zones-secondary.conf --out zones-primary.conf
296
+ ```
297
+
298
+ ### Full production workflow
299
+
300
+ ```bash
301
+ # On the primary server: generate the secondary config
302
+ bind-zone-sync gen --conf /usr/local/etc/namedb/zones-primary.conf \
303
+ --out /usr/local/etc/namedb/zones-secondary.conf \
304
+ --primaries "10.0.0.100;" \
305
+ --db-path-find /usr/local/etc/namedb/primary/ \
306
+ --db-path-replace /usr/local/etc/namedb/secondary/
307
+
308
+ # Deploy zones-secondary.conf to the secondary server
309
+
310
+ # If you need to restore a primary config from a secondary backup
311
+ bind-zone-sync restore --conf /usr/local/etc/namedb/zones-secondary.conf \
312
+ --out /usr/local/etc/namedb/zones-primary.conf \
313
+ --db-path-find /usr/local/etc/namedb/secondary/ \
314
+ --db-path-replace /usr/local/etc/namedb/primary/
315
+ ```
316
+
317
+ ### Legacy zones sync with catalog.zone
318
+
319
+ ```bash
320
+ # On the primary server — build zone config with type primary
321
+ bind-zone-sync convert --conf /usr/local/etc/namedb/zones/ \
322
+ --out /usr/local/etc/namedb/named.conf.zones
323
+
324
+ # On the secondary server — build zone config with type secondary
325
+ bind-zone-sync convert --conf /usr/local/etc/namedb/zones/ \
326
+ --out /usr/local/etc/namedb/named.conf.legacy-zones \
327
+ --primaries "10.0.0.100;"
328
+
329
+ # Build a catalog.zone zone list from named.conf (SHA1 keys)
330
+ bind-zone-sync catalog --conf /usr/local/etc/namedb/named.conf \
331
+ --out /usr/local/etc/namedb/catalog.zone
332
+
333
+ # Include the generated config in your main named.conf
334
+ # include "/usr/local/etc/namedb/named.conf.zones";
335
+ # include "/usr/local/etc/namedb/named.conf.legacy-zones";
336
+ # catalog "catalog.zone" { zones "/usr/local/etc/namedb/catalog.zone"; };
337
+ ```
@@ -0,0 +1,18 @@
1
+ [project]
2
+ name = "bind-zone-sync"
3
+ version = "0.2.0"
4
+ description = "Sync BIND zone configs between primary and secondary servers"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ dependencies = []
8
+
9
+ [[project.authors]]
10
+ name = "Lex SysKo"
11
+ email = "lexsys.ko@gmail.com"
12
+
13
+ [project.scripts]
14
+ bind-zone-sync = "bind_zone_sync.bind_zone_sync:main"
15
+
16
+ [build-system]
17
+ requires = ["uv_build>=0.13.4,<0.14.0"]
18
+ build-backend = "uv_build"
@@ -0,0 +1,17 @@
1
+ [project]
2
+ name = "bind-zone-sync"
3
+ version = "0.2.0"
4
+ description = "Sync BIND zone configs between primary and secondary servers"
5
+ readme = "README.md"
6
+ authors = [
7
+ { name = "Lex SysKo", email = "lexsys.ko@gmail.com" }
8
+ ]
9
+ requires-python = ">=3.12"
10
+ dependencies = []
11
+
12
+ [project.scripts]
13
+ bind-zone-sync = "bind_zone_sync.bind_zone_sync:main"
14
+
15
+ [build-system]
16
+ requires = ["uv_build>=0.13.4,<0.14.0"]
17
+ build-backend = "uv_build"
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()