1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
|
# Advanced argparse patterns with subcommands
import argparse
import sys
from typing import Optional
class PiHoleCLI:
"""Pi-hole command-line interface simulator"""
def __init__(self):
self.parser = self.create_parser()
def create_parser(self) -> argparse.ArgumentParser:
"""Create argument parser with subcommands"""
parser = argparse.ArgumentParser(
description="Pi-hole DNS management tool",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
pihole status # Show Pi-hole status
pihole enable # Enable DNS blocking
pihole disable 300 # Disable blocking for 5 minutes
pihole query google.com # Query domain status
pihole blacklist add ads.com # Add domain to blacklist
pihole whitelist remove safe.com # Remove from whitelist
pihole log tail -n 100 # Show last 100 log entries
"""
)
parser.add_argument(
'--config',
default='/etc/pihole/pihole-FTL.conf',
help='Path to Pi-hole configuration file'
)
parser.add_argument(
'-v', '--verbose',
action='store_true',
help='Enable verbose output'
)
# Create subparsers
subparsers = parser.add_subparsers(
dest='command',
help='Available commands',
metavar='COMMAND'
)
# Status command
status_parser = subparsers.add_parser(
'status',
help='Show Pi-hole status'
)
# Enable command
enable_parser = subparsers.add_parser(
'enable',
help='Enable DNS blocking'
)
# Disable command
disable_parser = subparsers.add_parser(
'disable',
help='Disable DNS blocking'
)
disable_parser.add_argument(
'duration',
type=int,
nargs='?',
default=0,
help='Disable duration in seconds (0 = permanently)'
)
# Query command
query_parser = subparsers.add_parser(
'query',
help='Query domain status'
)
query_parser.add_argument(
'domain',
help='Domain to query'
)
query_parser.add_argument(
'--type',
choices=['A', 'AAAA', 'MX', 'TXT'],
default='A',
help='DNS query type'
)
# Blacklist management
blacklist_parser = subparsers.add_parser(
'blacklist',
help='Manage blacklist'
)
blacklist_subparsers = blacklist_parser.add_subparsers(
dest='blacklist_action',
help='Blacklist actions'
)
# Blacklist add
blacklist_add = blacklist_subparsers.add_parser(
'add',
help='Add domains to blacklist'
)
blacklist_add.add_argument(
'domains',
nargs='+',
help='Domains to add'
)
blacklist_add.add_argument(
'--comment',
help='Comment for the entry'
)
# Blacklist remove
blacklist_remove = blacklist_subparsers.add_parser(
'remove',
help='Remove domains from blacklist'
)
blacklist_remove.add_argument(
'domains',
nargs='+',
help='Domains to remove'
)
# Blacklist list
blacklist_list = blacklist_subparsers.add_parser(
'list',
help='List blacklisted domains'
)
blacklist_list.add_argument(
'--grep',
help='Filter domains with grep pattern'
)
# Whitelist management (similar structure)
whitelist_parser = subparsers.add_parser(
'whitelist',
help='Manage whitelist'
)
whitelist_subparsers = whitelist_parser.add_subparsers(
dest='whitelist_action',
help='Whitelist actions'
)
whitelist_add = whitelist_subparsers.add_parser('add', help='Add domains to whitelist')
whitelist_add.add_argument('domains', nargs='+', help='Domains to add')
whitelist_remove = whitelist_subparsers.add_parser('remove', help='Remove domains from whitelist')
whitelist_remove.add_argument('domains', nargs='+', help='Domains to remove')
whitelist_list = whitelist_subparsers.add_parser('list', help='List whitelisted domains')
# Log management
log_parser = subparsers.add_parser(
'log',
help='Manage Pi-hole logs'
)
log_subparsers = log_parser.add_subparsers(
dest='log_action',
help='Log actions'
)
log_tail = log_subparsers.add_parser('tail', help='Tail log file')
log_tail.add_argument('-n', '--lines', type=int, default=10, help='Number of lines to show')
log_tail.add_argument('-f', '--follow', action='store_true', help='Follow log file')
log_grep = log_subparsers.add_parser('grep', help='Search log file')
log_grep.add_argument('pattern', help='Search pattern')
log_grep.add_argument('-i', '--ignore-case', action='store_true', help='Ignore case')
# Statistics
stats_parser = subparsers.add_parser(
'stats',
help='Show Pi-hole statistics'
)
stats_parser.add_argument(
'--format',
choices=['json', 'table', 'csv'],
default='table',
help='Output format'
)
return parser
def handle_command(self, args):
"""Handle parsed command arguments"""
if args.verbose:
print(f"Verbose mode enabled. Config: {args.config}")
if not args.command:
self.parser.print_help()
return
# Route to appropriate handler
handler_name = f"handle_{args.command}"
if hasattr(self, handler_name):
handler = getattr(self, handler_name)
handler(args)
else:
print(f"Command '{args.command}' not implemented yet")
def handle_status(self, args):
"""Handle status command"""
print("Pi-hole Status:")
print(" DNS Service: Active")
print(" Blocking: Enabled")
print(" Blocklists: 1,234,567 domains")
print(" Queries today: 12,345")
print(" Blocked today: 1,234 (10.0%)")
def handle_enable(self, args):
"""Handle enable command"""
print("Enabling Pi-hole DNS blocking...")
print("DNS blocking is now ENABLED")
def handle_disable(self, args):
"""Handle disable command"""
if args.duration > 0:
print(f"Disabling Pi-hole DNS blocking for {args.duration} seconds...")
else:
print("Disabling Pi-hole DNS blocking permanently...")
print("DNS blocking is now DISABLED")
def handle_query(self, args):
"""Handle query command"""
print(f"Querying {args.domain} ({args.type} record)...")
print(f"Domain: {args.domain}")
print(f"Status: Not blocked")
print(f"Response: 192.168.1.1")
def handle_blacklist(self, args):
"""Handle blacklist command"""
if args.blacklist_action == 'add':
print(f"Adding {len(args.domains)} domain(s) to blacklist:")
for domain in args.domains:
print(f" + {domain}")
if args.comment:
print(f" Comment: {args.comment}")
elif args.blacklist_action == 'remove':
print(f"Removing {len(args.domains)} domain(s) from blacklist:")
for domain in args.domains:
print(f" - {domain}")
elif args.blacklist_action == 'list':
print("Blacklisted domains:")
sample_domains = ['ads.example.com', 'tracker.evil.com', 'malware.bad.com']
for domain in sample_domains:
if not args.grep or args.grep in domain:
print(f" {domain}")
def handle_whitelist(self, args):
"""Handle whitelist command"""
action = args.whitelist_action
if action == 'add':
print(f"Adding {len(args.domains)} domain(s) to whitelist:")
for domain in args.domains:
print(f" + {domain}")
elif action == 'remove':
print(f"Removing {len(args.domains)} domain(s) from whitelist:")
for domain in args.domains:
print(f" - {domain}")
elif action == 'list':
print("Whitelisted domains:")
print(" google.com")
print(" github.com")
def handle_log(self, args):
"""Handle log command"""
if args.log_action == 'tail':
print(f"Showing last {args.lines} lines from Pi-hole log:")
if args.follow:
print("Following log file (Ctrl+C to stop)...")
# In real implementation, would tail actual log file
for i in range(args.lines):
print(f"2020-07-24 12:34:{i:02d} Query: example.com from 192.168.1.100")
elif args.log_action == 'grep':
print(f"Searching log for pattern: {args.pattern}")
if args.ignore_case:
print("Case-insensitive search enabled")
print("192.168.1.100 2020-07-24 12:34:56 example.com")
def handle_stats(self, args):
"""Handle stats command"""
stats = {
'dns_queries_today': 12345,
'ads_blocked_today': 1234,
'ads_percentage_today': 10.0,
'domains_being_blocked': 1234567,
'unique_domains': 5678,
'unique_clients': 15
}
if args.format == 'json':
import json
print(json.dumps(stats, indent=2))
elif args.format == 'csv':
print("metric,value")
for key, value in stats.items():
print(f"{key},{value}")
else: # table format
print("Pi-hole Statistics:")
print(f" DNS queries today: {stats['dns_queries_today']:,}")
print(f" Ads blocked today: {stats['ads_blocked_today']:,}")
print(f" Percentage blocked: {stats['ads_percentage_today']:.1f}%")
print(f" Domains being blocked: {stats['domains_being_blocked']:,}")
print(f" Unique domains: {stats['unique_domains']:,}")
print(f" Unique clients: {stats['unique_clients']}")
def run(self, args=None):
"""Run the CLI application"""
if args is None:
args = sys.argv[1:]
parsed_args = self.parser.parse_args(args)
self.handle_command(parsed_args)
# Usage examples
if __name__ == "__main__":
cli = PiHoleCLI()
# Test various commands
test_commands = [
['status'],
['query', 'google.com', '--type', 'A'],
['blacklist', 'add', 'ads.com', 'tracker.com', '--comment', 'Ad domains'],
['whitelist', 'list'],
['log', 'tail', '-n', '5'],
['stats', '--format', 'json'],
['disable', '300']
]
for cmd in test_commands:
print(f"\n> pihole {' '.join(cmd)}")
print("-" * 50)
cli.run(cmd)
|