-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSplunkManager.py
More file actions
1038 lines (868 loc) Β· 42.7 KB
/
Copy pathSplunkManager.py
File metadata and controls
1038 lines (868 loc) Β· 42.7 KB
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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import subprocess
import getpass
import time
import webbrowser
import zipfile
import platform
from tkinter import Tk, filedialog, messagebox
import tkinter as tk
# Initialize colorama on Windows
if platform.system() == 'Windows':
import colorama
colorama.init()
# βββββββββββββββββββββββββββββββββββββββββββββββββ
# Splunk Index Manager v0.5
# Developed by Jacob Wilson β’ dfirvault@gmail.com
# βββββββββββββββββββββββββββββββββββββββββββββββββ
class Style:
HEADER = "β" * 60
SUCCESS = "β"
ERROR = "β"
WARNING = "β "
INFO = "βΉ"
PROMPT = "β€"
DIVIDER = "β" * 60
BLUE = "\033[94m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BOLD = "\033[1m"
END = "\033[0m"
def print_header():
print(f"\n{Style.BLUE}{Style.HEADER}{Style.END}")
print(f"{Style.BOLD}{Style.BLUE} Splunk Index Manager {Style.END}v0.5")
print(f" {Style.BLUE}Developed by Jacob Wilson β’ dfirvault@gmail.com{Style.END}")
print(f"{Style.BLUE}{Style.HEADER}{Style.END}\n")
print_header()
CONFIG_FILE = "config.txt"
DEFAULT_SPLUNK_PATHS = [
"/opt/splunk/bin/splunk",
"C:\\Program Files\\Splunk\\bin\\splunk.exe",
"/Applications/Splunk/bin/splunk"
]
class SplunkManager:
def __init__(self):
self.splunk_path = ""
self.username = ""
self.password = ""
self.load_config()
self.verify_splunk()
def show_progress(self, message, duration=2):
"""Show a spinning progress animation"""
spinner = ['β£Ύ','β£½','β£»','β’Ώ','β‘Ώ','β£','β£―','β£·']
end_time = time.time() + duration
i = 0
while time.time() < end_time:
print(f"\r{Style.BLUE}{spinner[i % len(spinner)]}{Style.END} {message}", end="")
time.sleep(0.1)
i += 1
print("\r" + " " * (len(message) + 2) + "\r", end="")
def print_success(self, message):
print(f"{Style.GREEN}{Style.SUCCESS} {message}{Style.END}")
def print_error(self, message):
print(f"{Style.RED}{Style.ERROR} {message}{Style.END}")
def print_warning(self, message):
print(f"{Style.YELLOW}{Style.WARNING} {message}{Style.END}")
def print_info(self, message):
print(f"{Style.BLUE}{Style.INFO} {message}{Style.END}")
def print_divider(self):
print(f"{Style.BLUE}{Style.DIVIDER}{Style.END}")
def load_config(self):
if os.path.exists(CONFIG_FILE):
try:
with open(CONFIG_FILE, 'r') as f:
config = json.load(f)
self.splunk_path = config.get('splunk_path', '')
self.username = config.get('username', '')
self.password = config.get('password', '')
except:
pass
if not self.splunk_path or not os.path.exists(self.splunk_path):
self.prompt_splunk_path()
if not self.username or not self.password:
self.prompt_credentials()
self.save_config()
def prompt_splunk_path(self):
root = Tk()
root.withdraw()
for path in DEFAULT_SPLUNK_PATHS:
if os.path.exists(path):
use_default = messagebox.askyesno(
"Splunk Path Found",
f"Splunk binary found at {path}. Use this location?"
)
if use_default:
self.splunk_path = path
root.destroy()
return
messagebox.showinfo("Splunk Path", "Please select the Splunk binary (splunk or splunk.exe)")
self.splunk_path = filedialog.askopenfilename(title="Select Splunk binary")
root.destroy()
def prompt_credentials(self):
print(f"\n{Style.YELLOW}π Splunk Credentials Required{Style.END}")
self.username = input(f"{Style.PROMPT} Enter Splunk username: ")
self.password = getpass.getpass(f"{Style.PROMPT} Enter Splunk password: ")
def save_config(self):
with open(CONFIG_FILE, 'w') as f:
json.dump({
'splunk_path': self.splunk_path,
'username': self.username,
'password': self.password
}, f)
def verify_splunk(self):
if not os.path.exists(self.splunk_path):
self.print_error("Splunk binary not found at specified path.")
self.prompt_splunk_path()
self.save_config()
self.show_progress("Verifying Splunk connection...")
test_cmd = [
self.splunk_path,
'login',
'-auth',
f'{self.username}:{self.password}'
]
try:
result = subprocess.run(test_cmd, capture_output=True, text=True)
if "Login failed" in result.stderr:
self.print_error("Login failed with provided credentials.")
self.prompt_credentials()
self.save_config()
self.verify_splunk()
else:
self.print_success("Successfully connected to the local Splunk service! http://127.0.0.1:8000/")
print(f"{Style.BLUE}β’{Style.END} Using Splunk binary at: {self.splunk_path}")
print(f"{Style.BLUE}β’{Style.END} Authenticated as user: {self.username}\n")
except Exception as e:
self.print_error(f"Error testing Splunk connection: {e}")
self.prompt_splunk_path()
self.save_config()
self.verify_splunk()
def run_splunk_command(self, command):
full_cmd = [self.splunk_path] + command
try:
result = subprocess.run(
full_cmd,
capture_output=True,
text=True,
shell=True if os.name == 'nt' else False,
env={**os.environ, 'SPLUNK_CLI_SERVER_CERT_VERIFY': '0'}
)
filtered_output = '\n'.join(line for line in result.stdout.split('\n')
if 'Server Certificate Hostname Validation' not in line)
filtered_errors = '\n'.join(line for line in result.stderr.split('\n')
if 'Server Certificate Hostname Validation' not in line)
return filtered_output + filtered_errors
except Exception as e:
self.print_error(f"Error running Splunk command: {e}")
return None
def index_exists(self, index_name):
"""Check if an index exists in Splunk"""
indexes = self.list_indexes()
return index_name in indexes
def restore_backup(self, backup_file):
"""Restore an index from backup zip file"""
self.show_progress("Preparing to restore backup...")
splunk_db = os.path.join(
os.path.dirname(os.path.dirname(self.splunk_path)),
'var', 'lib', 'splunk'
)
if not os.path.exists(backup_file):
return False, "Backup file not found"
print(f"\n{Style.BLUE}β» Restoring backup from:{Style.END} {backup_file}")
print(f"{Style.BLUE}β’{Style.END} Target location: {splunk_db}")
# Check if the backup is encrypted and if we have pyzipper
is_encrypted = False
try:
# First try with standard zipfile
with zipfile.ZipFile(backup_file, 'r') as test_zip:
try:
test_zip.testzip()
except RuntimeError as e:
if 'encrypted' in str(e):
is_encrypted = True
except Exception as e:
return False, f"Unable to read backup file: {str(e)}"
password = None
if is_encrypted:
print(f"\n{Style.YELLOW}π This backup is password protected{Style.END}")
password = getpass.getpass(f"{Style.PROMPT} Enter backup password: ")
try:
# Extract the index name from the backup filename
base_name = os.path.basename(backup_file)
index_name = base_name.split('_backup_')[0]
# Track what we're restoring
restoring_dat = False
restoring_folder = False
# Determine which library to use for extraction
use_pyzipper = False
if is_encrypted:
try:
import pyzipper
use_pyzipper = True
except ImportError:
self.print_warning("pyzipper not available, falling back to standard zipfile for encrypted backup")
self.print_warning("For better compatibility with encrypted backups, install pyzipper: pip install pyzipper")
if use_pyzipper:
# Use pyzipper for encrypted backups
with pyzipper.AESZipFile(backup_file, 'r') as zip_ref:
if password:
zip_ref.setpassword(password.encode('utf-8'))
# First check what we have in the backup
for file in zip_ref.namelist():
if file.endswith('.dat'):
restoring_dat = True
elif file.startswith(f'{index_name}/'):
restoring_folder = True
# Restore .dat file if present
if restoring_dat:
dat_file = f"{index_name}.dat"
print(f"\n{Style.BLUE}β³ Restoring {dat_file}...{Style.END}")
try:
zip_ref.extract(dat_file, splunk_db)
print(f" {Style.GREEN}β{Style.END} Restored {dat_file} to {splunk_db}")
except RuntimeError as e:
if 'Bad password' in str(e):
return False, "Incorrect password provided for encrypted backup"
raise
# Restore folder if present
if restoring_folder:
print(f"\n{Style.BLUE}β³ Restoring {index_name} folder...{Style.END}")
file_count = 0
for file in zip_ref.namelist():
if file.startswith(f'{index_name}/'):
try:
zip_ref.extract(file, splunk_db)
file_count += 1
if file_count % 10 == 0:
print(f"\r {Style.BLUE}β’{Style.END} Restored {file_count} files...", end="")
except RuntimeError as e:
if 'Bad password' in str(e):
return False, "Incorrect password provided for encrypted backup"
raise
print(f"\r {Style.GREEN}β{Style.END} Restored {file_count} files to {index_name} folder")
else:
# Use standard zipfile for unencrypted or fallback for encrypted
with zipfile.ZipFile(backup_file, 'r') as zip_ref:
if password:
zip_ref.setpassword(password.encode('utf-8'))
# First check what we have in the backup
for file in zip_ref.namelist():
if file.endswith('.dat'):
restoring_dat = True
elif file.startswith(f'{index_name}/'):
restoring_folder = True
# Restore .dat file if present
if restoring_dat:
dat_file = f"{index_name}.dat"
print(f"\n{Style.BLUE}β³ Restoring {dat_file}...{Style.END}")
try:
zip_ref.extract(dat_file, splunk_db)
print(f" {Style.GREEN}β{Style.END} Restored {dat_file} to {splunk_db}")
except RuntimeError as e:
if 'Bad password' in str(e):
return False, "Incorrect password provided for encrypted backup"
elif 'compression method' in str(e):
return False, "Compression method not supported - try installing pyzipper: pip install pyzipper"
raise
# Restore folder if present
if restoring_folder:
print(f"\n{Style.BLUE}β³ Restoring {index_name} folder...{Style.END}")
file_count = 0
for file in zip_ref.namelist():
if file.startswith(f'{index_name}/'):
try:
zip_ref.extract(file, splunk_db)
file_count += 1
if file_count % 10 == 0:
print(f"\r {Style.BLUE}β’{Style.END} Restored {file_count} files...", end="")
except RuntimeError as e:
if 'Bad password' in str(e):
return False, "Incorrect password provided for encrypted backup"
elif 'compression method' in str(e):
return False, "Compression method not supported - try installing pyzipper: pip install pyzipper"
raise
print(f"\r {Style.GREEN}β{Style.END} Restored {file_count} files to {index_name} folder")
# Verify the index exists in Splunk
if not self.index_exists(index_name):
print(f"\n{Style.BLUE}β³ Creating index {index_name} in Splunk...{Style.END}")
success, message = self.create_index(index_name)
if not success:
return False, f"Restore failed: {message}"
# Update indexes.conf
conf_updated = self.update_indexes_conf(index_name)
return True, (f"\n{Style.GREEN}β Restore completed successfully!{Style.END}\n"
f"{Style.BLUE}Index:{Style.END} {index_name}\n"
f"{Style.BLUE}Location:{Style.END} {splunk_db}\n"
f"{Style.BLUE}Configuration:{Style.END} {'updated' if conf_updated else 'update attempted'}\n"
f"{Style.YELLOW}Note:{Style.END} You may need to manually restart Splunk for changes to take effect")
except Exception as e:
return False, f"Restore failed: {str(e)}"
def create_index(self, index_name):
self.show_progress(f"Creating index '{index_name}'...")
result = self.run_splunk_command([
'add', 'index', index_name,
'-auth', f'{self.username}:{self.password}'
])
if result is None:
return False, "Failed to execute Splunk command"
normalized_output = ' '.join(result.lower().split())
success_phrases = ['created', 'added', 'already exists', 'index created']
if any(phrase in normalized_output for phrase in success_phrases):
return True, f"Index '{index_name}' created successfully."
elif "error" in normalized_output or "failed" in normalized_output:
return False, f"Splunk error: {result.strip()}"
return False, f"Unexpected response: {result.strip()}"
def get_index_size(self, index_name):
splunk_db = os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'var', 'lib', 'splunk')
index_path = os.path.join(splunk_db, index_name)
if not os.path.exists(index_path):
return 0
total_size = 0
for dirpath, _, filenames in os.walk(index_path):
for f in filenames:
fp = os.path.join(dirpath, f)
try:
total_size += os.path.getsize(fp)
except:
continue
return total_size
def format_size(self, bytes):
mb = bytes / (1024 * 1024)
if mb > 2000:
return f"{mb / 1024:.1f}GB"
return f"{mb:.1f}MB"
def list_indexes(self, exclude_system=True):
self.show_progress("Fetching list of indexes...")
result = self.run_splunk_command([
'list', 'index',
'-auth', f'{self.username}:{self.password}'
])
if not result:
return []
excluded_indexes = {'_', 'summary', 'splunklogger', "main", 'history'} if exclude_system else set()
indexes = []
for line in result.split('\n'):
line = line.strip()
if not line or '\\' in line or '/' in line:
continue
if any(line.lower().startswith(excluded) for excluded in excluded_indexes):
continue
size_bytes = self.get_index_size(line)
size_str = self.format_size(size_bytes)
indexes.append(f"{line} - {size_str}")
return indexes
def delete_index(self, index_name):
self.show_progress(f"Deleting index '{index_name}'...")
result = self.run_splunk_command([
'remove', 'index', index_name,
'-auth', f'{self.username}:{self.password}'
])
if result is None:
return False, "Failed to execute Splunk command"
normalized_output = ' '.join(result.lower().split())
success_phrases = ['removed', 'deleted', 'removal of index', 'successfully']
windows_success_phrases = ['admin handler not found']
if (any(phrase in normalized_output for phrase in success_phrases) or
(os.name == 'nt' and any(phrase in normalized_output for phrase in windows_success_phrases))):
conf_updated = self.remove_index_from_conf(index_name)
if conf_updated:
return True, f"Index '{index_name}' deleted successfully and removed from indexes.conf"
else:
return True, (f"Index '{index_name}' deleted successfully but could not update indexes.conf\n"
f"You may need to manually remove the [{index_name}] section")
elif "error" in normalized_output or "failed" in normalized_output:
return False, f"Splunk error: {result.strip()}"
return False, f"Unexpected response: {result.strip()}"
def remove_index_from_conf(self, index_name):
conf_locations = [
os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'etc', 'system', 'local', 'indexes.conf'),
os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'etc', 'apps', 'search', 'local', 'indexes.conf'),
os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'etc', 'system', 'default', 'indexes.conf')
]
conf_path = None
for path in conf_locations:
if os.path.exists(path):
conf_path = path
break
if not conf_path:
root = Tk()
root.withdraw()
messagebox.showinfo("indexes.conf Location", "Could not automatically find indexes.conf.")
conf_path = filedialog.askopenfilename(title="Select indexes.conf file", filetypes=[("Config files", "*.conf")])
root.destroy()
if not conf_path:
return False
try:
with open(conf_path, 'r') as f:
content = f.read()
start_idx = content.find(f"[{index_name}]")
if start_idx == -1:
return True
end_idx = content.find("\n[", start_idx)
if end_idx == -1:
end_idx = len(content)
else:
end_idx = content.rfind("\n", start_idx, end_idx)
new_content = content[:start_idx] + content[end_idx:]
with open(conf_path, 'w') as f:
f.write(new_content)
self.print_info(f"Removed [{index_name}] section from {conf_path}")
return True
except Exception as e:
self.print_warning(f"Could not update indexes.conf: {str(e)}")
return False
# ====================== NEW FUNCTIONALITY ======================
def reload_monitor_inputs(self):
"""Reload monitor inputs without restarting Splunk"""
self.show_progress("Reloading monitor inputs...")
result = self.run_splunk_command([
'_internal', 'call', '/services/data/inputs/monitor/_reload',
'-auth', f'{self.username}:{self.password}'
])
if result is None:
self.print_error("Failed to execute reload command.")
return False
# Check for success indicators
if "200" in result or "success" in result.lower() or "reload" in result.lower():
self.print_success("Monitor inputs reloaded successfully!")
self.print_info("New folders should now be monitored (may take a few seconds to start).")
return True
else:
self.print_warning("Reload command executed but response was unexpected.")
self.print_info(f"Raw response: {result.strip()}")
return False
def add_monitor_to_inputs_conf(self, folder_path, index_name):
if not folder_path or not index_name:
self.print_error("Invalid folder path or index name.")
return False
splunk_home = os.path.dirname(os.path.dirname(self.splunk_path))
inputs_conf_dir = os.path.join(splunk_home, 'etc', 'apps', 'search', 'local')
inputs_conf_path = os.path.join(inputs_conf_dir, 'inputs.conf')
os.makedirs(inputs_conf_dir, exist_ok=True)
# Normalize path for cross-platform compatibility
monitor_path = os.path.normpath(folder_path)
try:
stanza_header = f"[monitor://{monitor_path}]"
# Read existing content if file exists
if os.path.exists(inputs_conf_path):
with open(inputs_conf_path, 'r', encoding='utf-8') as f:
content = f.read()
# Check if this exact monitor stanza already exists
if stanza_header in content:
# Find the full stanza block and check what index is currently set
lines = content.splitlines()
in_target_stanza = False
current_index = None
for line in lines:
stripped = line.strip()
if stripped.startswith('[') and stripped.endswith(']'):
if stripped == stanza_header:
in_target_stanza = True
else:
in_target_stanza = False
if in_target_stanza and stripped.startswith('index ='):
current_index = stripped.split('=', 1)[1].strip()
# If the index is already correct β do nothing
if current_index == index_name:
self.print_warning(f"Monitor for '{monitor_path}' already exists with index '{index_name}'.")
return True
# If the path exists but index is different β update it
elif current_index is not None:
self.print_info(f"Monitor for '{monitor_path}' exists but uses index '{current_index}'. Updating to '{index_name}'...")
# Rebuild content with updated index
new_content = []
in_target_stanza = False
for line in lines:
stripped = line.strip()
if stripped.startswith('[') and stripped.endswith(']'):
in_target_stanza = (stripped == stanza_header)
if in_target_stanza and stripped.startswith('index ='):
new_content.append(f"index = {index_name}")
else:
new_content.append(line)
with open(inputs_conf_path, 'w', encoding='utf-8') as f:
f.write('\n'.join(new_content))
self.print_success(f"Successfully updated index to '{index_name}' for monitor:")
print(f" {Style.BLUE}Path:{Style.END} {monitor_path}")
print(f" {Style.BLUE}Index:{Style.END} {index_name}")
print(f" {Style.BLUE}Config:{Style.END} {inputs_conf_path}")
self.print_info("Note: Restart Splunk (or reload inputs) for changes to take effect.")
return True
# If we reach here, either file doesn't exist or stanza doesn't exist β append new stanza
stanza = f"""
[monitor://{monitor_path}]
disabled = false
host = dfir-server
index = {index_name}
"""
with open(inputs_conf_path, 'a', encoding='utf-8') as f:
f.write(stanza)
self.print_success(f"Successfully added monitor for folder:")
print(f" {Style.BLUE}Path:{Style.END} {monitor_path}")
print(f" {Style.BLUE}Index:{Style.END} {index_name}")
print(f" {Style.BLUE}Config:{Style.END} {inputs_conf_path}")
self.print_info("Note: Restart Splunk (or reload inputs) for the new monitor to take effect.")
return True
except Exception as e:
self.print_error(f"Failed to update inputs.conf: {str(e)}")
return False
# ================== NEW: OPEN SPLUNK WEB ==================
def open_splunk_web(self, index_name=None):
"""Open Splunk Web in the default browser, optionally with a specific index pre-loaded"""
if index_name:
# URL with pre-filled search for the specific index
encoded_index = index_name.replace('"', '%22') # just in case, but usually not needed
url = (
f"http://localhost:8000/en-US/app/search/search?"
f"q=search%20index%3D%22{encoded_index}%22"
f"&earliest=0&latest="
f"&display.page.search.mode=smart"
f"&dispatch.sample_ratio=1"
)
self.print_info(f"Opening Splunk Web with index '{index_name}' β {url}")
else:
# Default behavior - just open Splunk Web
url = "http://127.0.0.1:8000"
self.print_info(f"Opening Splunk Web β {url}")
try:
webbrowser.open(url, new=2) # new=2 opens in new tab/window
self.print_success("Splunk Web should now be open in your browser.")
print(f"{Style.BLUE}β’{Style.END} URL: {url}")
except Exception as e:
self.print_error(f"Could not open browser automatically: {e}")
print(f"\n{Style.BLUE}Please open this URL manually:{Style.END}")
print(f" {Style.GREEN}{url}{Style.END}")
def update_indexes_conf(self, index_name):
"""Update indexes.conf with the restored index configuration"""
self.show_progress(f"Updating indexes.conf for {index_name}...")
# Try to find indexes.conf in common locations
conf_locations = [
os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'etc', 'system', 'local', 'indexes.conf'),
os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'etc', 'apps', 'search', 'local', 'indexes.conf'),
os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'etc', 'system', 'default', 'indexes.conf')
]
conf_path = None
for path in conf_locations:
if os.path.exists(path):
conf_path = path
break
if not conf_path:
# If we can't find it, ask the user
root = Tk()
root.withdraw()
messagebox.showinfo(
"indexes.conf Location",
"Could not automatically find indexes.conf.\n"
"It's typically located in:\n"
"etc/system/local/ or etc/apps/search/local/"
)
conf_path = filedialog.askopenfilename(
title="Select indexes.conf file",
filetypes=[("Config files", "*.conf")]
)
root.destroy()
if not conf_path:
self.print_warning("Could not update indexes.conf - index paths may need manual configuration")
return False
# Configuration to add
config_content = f"""
[{index_name}]
coldPath = $SPLUNK_DB\\{index_name}\\colddb
enableDataIntegrityControl = 0
enableTsidxReduction = 0
homePath = $SPLUNK_DB\\{index_name}\\db
maxTotalDataSizeMB = 512000
thawedPath = $SPLUNK_DB\\{index_name}\\thaweddb
"""
try:
# Check if the index already exists in the config
with open(conf_path, 'r') as f:
content = f.read()
# If the index section already exists, we'll replace it
if f"[{index_name}]" in content:
# Find the existing section and remove it
start_idx = content.find(f"[{index_name}]")
end_idx = content.find("\n\n", start_idx) # Look for double newline as section end
if end_idx == -1:
end_idx = len(content)
new_content = content[:start_idx] + config_content + content[end_idx:]
else:
# Just append the new configuration
new_content = content + "\n" + config_content
# Write the updated content back to the file
with open(conf_path, 'w') as f:
f.write(new_content)
self.print_success(f"Updated {conf_path} with {index_name} configuration")
return True
except Exception as e:
self.print_warning(f"Could not update indexes.conf: {str(e)}")
self.print_warning("You may need to manually add the index configuration")
return False
# ================== UPDATED MENUS ==================
def main_menu(self):
while True:
self.print_divider()
print(f"\n{Style.BOLD}{Style.BLUE}π Splunk Index Management Tool{Style.END}")
print(f"{Style.BLUE}1:{Style.END} π Create an index and monitor folder")
print(f"{Style.BLUE}2:{Style.END} π Monitor folder (existing index)")
print(f"{Style.BLUE}3:{Style.END} π Manage indexes")
print(f"{Style.BLUE}4:{Style.END} πΎ Restore from backup")
print(f"{Style.BLUE}5:{Style.END} π Open Splunk Web")
print(f"{Style.BLUE}0:{Style.END} πͺ Exit")
choice = input(f"\n{Style.PROMPT} Enter your choice: ").strip()
if choice == "1":
self.create_index_menu()
elif choice == "2":
self.monitor_folder_menu()
elif choice == "3":
self.manage_indexes_menu()
elif choice == "4":
self.restore_backup_menu()
elif choice == "5":
self.open_splunk_web()
elif choice == "0":
self.print_success("Goodbye!")
break
else:
self.print_error("Invalid choice.")
def create_index_menu(self):
self.print_divider()
print(f"\n{Style.BOLD}π Create an Index and Monitor Folder{Style.END}")
index_name = input(f"{Style.PROMPT} Enter the name for the new index: ").strip()
if not index_name:
self.print_error("Index name cannot be empty.")
return
success, message = self.create_index(index_name)
if not success:
self.print_error(message)
return
self.print_success(message)
# Ask if user wants to monitor a folder immediately
if input(f"\n{Style.PROMPT} Would you like to monitor a folder for this index now? (y/n): ").strip().lower() == 'y':
root = Tk()
root.withdraw()
folder_path = filedialog.askdirectory(title=f"Select folder to monitor for index: {index_name}")
root.destroy()
if folder_path:
self.add_monitor_to_inputs_conf(folder_path, index_name)
self.reload_monitor_inputs()
self.open_splunk_web(index_name)
else:
self.print_warning("Folder selection cancelled.")
def monitor_folder_menu(self):
self.print_divider()
print(f"\n{Style.BOLD}π Monitor Folder for Existing Index{Style.END}")
indexes = self.list_indexes()
if not indexes:
self.print_warning("No non-system indexes found.")
return
print(f"\n{Style.BLUE}π Available indexes:{Style.END}")
for i, index in enumerate(indexes, 1):
print(f"{Style.BLUE}{i}:{Style.END} {index}")
print(f"{Style.BLUE}0:{Style.END} β© Back to main menu")
try:
choice = input(f"\n{Style.PROMPT} Select an index: ").strip()
if choice == "0":
return
choice = int(choice)
if not (1 <= choice <= len(indexes)):
self.print_error("Invalid selection.")
return
index_display = indexes[choice - 1]
index_name = index_display.split(' - ')[0].strip()
print(f"\n{Style.BLUE}π Select the folder you want to monitor for index '{index_name}'{Style.END}")
root = Tk()
root.withdraw()
folder_path = filedialog.askdirectory(title=f"Select folder to monitor β Index: {index_name}")
root.destroy()
if folder_path:
self.add_monitor_to_inputs_conf(folder_path, index_name)
self.reload_monitor_inputs()
self.open_splunk_web(index_name)
else:
self.print_warning("Folder selection cancelled.")
except ValueError:
self.print_error("Please enter a valid number.")
def manage_indexes_menu(self):
self.print_divider()
print(f"\n{Style.BOLD}π Manage Indexes{Style.END}")
indexes = self.list_indexes()
if not indexes:
self.print_warning("No non-system indexes found.")
return
print(f"\n{Style.BLUE}π Available indexes:{Style.END}")
for i, index in enumerate(indexes, 1):
print(f"{Style.BLUE}{i}:{Style.END} {index}")
print(f"{Style.BLUE}0:{Style.END} β© Back to main menu")
try:
choice = input(f"\n{Style.PROMPT} Select an index to manage: ").strip()
if choice == "0":
return
choice = int(choice)
if 1 <= choice <= len(indexes):
self.index_operations_menu(indexes[choice-1])
else:
self.print_error("Invalid selection.")
except ValueError:
self.print_error("Please enter a number.")
def index_operations_menu(self, index_display):
index_name = index_display.split(' - ')[0].strip()
while True:
self.print_divider()
print(f"\n{Style.BOLD}π Operations for index:{Style.END} {Style.BLUE}{index_display}{Style.END}")
print(f"{Style.BLUE}1:{Style.END} π Delete index")
print(f"{Style.BLUE}2:{Style.END} πΎ Backup index")
print(f"{Style.BLUE}3:{Style.END} πΎπ Backup and delete index")
print(f"{Style.BLUE}0:{Style.END} β© Back to index list")
choice = input(f"\n{Style.PROMPT} Enter your choice: ").strip()
if choice == "1":
confirm = input(f"\n{Style.RED}β Are you absolutely sure you want to permanently delete index '{index_name}'? (y/n): {Style.END}")
if confirm.lower() == 'y':
success, message = self.delete_index(index_name)
if success:
self.print_success(message)
else:
self.print_error(message)
else:
self.print_warning("Index deletion cancelled.")
break
elif choice == "2":
self.backup_index_menu(index_name)
break
elif choice == "3":
if self.backup_index_menu(index_name):
confirm = input(f"\n{Style.RED}β Are you absolutely sure you want to permanently delete index '{index_name}'? (y/n): {Style.END}")
if confirm.lower() == 'y':
success, message = self.delete_index(index_name)
if success:
self.print_success(message)
else:
self.print_error(message)
else:
self.print_warning("Index deletion cancelled.")
break
elif choice == "0":
break
else:
self.print_error("Invalid choice, please try again.")
def backup_index_menu(self, index_name):
print(f"\n{Style.BLUE}π Select backup directory{Style.END}")
backup_dir = input(f"{Style.PROMPT} Enter backup directory path (or leave blank to browse): ").strip()
if not backup_dir:
root = Tk()
root.withdraw()
backup_dir = filedialog.askdirectory(title="Select backup directory")
root.destroy()
if not backup_dir:
self.print_warning("Backup cancelled.")
return False
password = None
if input(f"{Style.PROMPT} Would you like to password protect the backup? (y/n): ").strip().lower() == 'y':
password = getpass.getpass(f"{Style.PROMPT} Enter backup password: ")
success, message = self.backup_index(index_name, backup_dir, password)
if success:
self.print_success(message)
else:
self.print_error(message)
return success
def restore_backup_menu(self):
self.print_divider()
print(f"\n{Style.BOLD}πΎ Restore from Backup{Style.END}")
root = Tk()
root.withdraw()
backup_file = filedialog.askopenfilename(title="Select backup file to restore", filetypes=[("ZIP files", "*.zip")])
root.destroy()
if not backup_file:
self.print_warning("Restore cancelled.")
return
if not self.confirm_restore():
self.print_warning("Restore cancelled.")
return
success, message = self.restore_backup(backup_file)
if success:
self.print_success(message)
else:
self.print_error(message)
def confirm_restore(self):
root = Tk()
root.withdraw()
response = messagebox.askyesno("Confirm Restore", "WARNING: This will overwrite any existing index data.\n\nAre you sure you want to continue?")
root.destroy()
return response
# ====================== BACKUP & RESTORE (unchanged from your original) ======================
def backup_index(self, index_name, backup_dir, password=None):
splunk_db = os.path.join(os.path.dirname(os.path.dirname(self.splunk_path)), 'var', 'lib', 'splunk')
index_folder = os.path.join(splunk_db, index_name)
dat_file = os.path.join(splunk_db, f"{index_name}.dat")
print(f"\n{Style.BLUE}π¦ Backing up index data from:{Style.END}")
if os.path.exists(dat_file):
print(f" {Style.BLUE}β’{Style.END} DAT file: {dat_file}")
print(f" {Style.BLUE}β’{Style.END} Index folder: {index_folder}")
if not os.path.exists(index_folder) and not os.path.exists(dat_file):
return False, f"No index data found"
if not os.path.exists(backup_dir):
os.makedirs(backup_dir)
zip_filename = os.path.join(backup_dir, f"{index_name}_backup_{time.strftime('%Y%m%d-%H%M%S')}.zip")
try:
with zipfile.ZipFile(zip_filename, 'w', zipfile.ZIP_DEFLATED) as zipf:
if password:
zipf.setpassword(password.encode('utf-8'))
self.print_warning("Using weak ZIP encryption")
if os.path.exists(dat_file):
zipf.write(dat_file, os.path.basename(dat_file))
if os.path.exists(index_folder):
for root, dirs, files in os.walk(index_folder):
for file in files:
file_path = os.path.join(root, file)
arcname = os.path.join(os.path.basename(index_folder), os.path.relpath(file_path, index_folder))
zipf.write(file_path, arcname)
return True, f"Backup completed successfully!\nLocation: {zip_filename}"
except Exception as e:
return False, f"Backup failed: {str(e)}"
def restore_backup_menu(self):
"""Menu for restoring from backup"""
self.print_divider()
print(f"\n{Style.BOLD}πΎ Restore from Backup{Style.END}")
root = Tk()
root.withdraw()
backup_file = filedialog.askopenfilename(
title="Select backup file to restore",
filetypes=[("ZIP files", "*.zip")]
)
root.destroy()