-
Notifications
You must be signed in to change notification settings - Fork 0
/
xgrep.py
154 lines (123 loc) Β· 6.62 KB
/
xgrep.py
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
import os
import re
import time
from datetime import timedelta
from termcolor import colored
import random
import string
import math
print("""
__ ____ _ _ __ ___ _ __
\ \/ / _` | '__/ _ \ '_ \
> < (_| | | | __/ |_) |
/_/\_\__, |_| \___| .__/
__/ | | |
|___/ |_|
by @kitsuiwebster
""")
def search_files(directory, keyword, context=100, verbose=True, chunk_size=1024 * 1024 * 8):
results = []
start_time = time.time()
last_update = start_time
try:
for root, _, files in os.walk(directory):
if verbose:
print(f'π Searching in directory: {root}')
for file in files:
if file.startswith('xgrep-'):
continue
if file.endswith(('.txt', '.sql', '.json', '.csv', '.html', 'log', '.php', '.pl', '.css', '.py', '.js', '.ts',
'.cgi', '.xml', 'jsx', '.cfm')):
file_path = os.path.join(root, file)
file_size = os.path.getsize(file_path)
if verbose:
print(f'π {file_path}')
if file_size > 5 * 1024 * 1024 * 1024:
print(f'β οΈ This file is large {math.ceil(file_size / (1024 * 1024 * 1024))} GB.')
print('β οΈ It can take a moment to be scanned. Be patient amigo.')
with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
data = ""
keyword_len = len(keyword)
while True:
chunk = f.read(chunk_size)
data += chunk
if len(chunk) < chunk_size:
matches = re.finditer(keyword, data, re.IGNORECASE)
for match in matches:
start, end = match.span()
left_context = max(0, start - context)
right_context = min(len(data), end + context + 1)
context_text = data[left_context:right_context]
keyword_match = colored(data[start:end], 'green')
result = {
'file': file_path,
'match': f"{context_text[:start - left_context]}{keyword_match}{context_text[end - left_context:]}",
'start': start + left_context,
'end': end + left_context,
}
results.append(result)
found_element = colored("Found one element", "green")
print(f"β
{found_element}")
break
else:
matches = re.finditer(keyword, data[:-keyword_len + 1], re.IGNORECASE)
for match in matches:
start, end = match.span()
left_context = max(0, start - context)
right_context = min(len(data), end + context + 1)
context_text = data[left_context:right_context]
keyword_match = colored(data[start:end], 'green')
result = {
'file': file_path,
'match': f"{context_text[:start - left_context]}{keyword_match}{context_text[end - left_context:]}",
'start': start + left_context,
'end': end + left_context,
}
results.append(result)
found_element = colored("Found one element", "green")
print(f"β
{found_element}")
data = data[-keyword_len + 1:]
current_time = time.time()
elapsed_time = current_time - start_time
if elapsed_time >= 10 and current_time - last_update >= 10:
elapsed_time_formatted = str(timedelta(seconds=elapsed_time))
print(f"β° Time elapsed: {elapsed_time_formatted}")
last_update = current_time
except PermissionError as e:
print(f"β Error: {e}")
except FileNotFoundError as e:
print(f"β Error: {e}")
except Exception as e:
print(f"β Unexpected error: {e}")
total_time = time.time() - start_time
total_time_formatted = str(timedelta(seconds=total_time))
print("\nβ
Search completed!")
print(f"β° Total time: {total_time_formatted}")
return results
if __name__ == '__main__':
current_directory = os.path.abspath(os.curdir)
keyword = input('π Enter the keyword to search for: ')
context_input = input(f'π Enter the number of characters around the keyword (press Enter for default: {100}): ')
context = 100 if context_input == '' else int(context_input)
chunk_size_options = [1024 * x for x in [8, 1024, 262144, 1048576, 2097152]]
print('π Enter the chunk size\n')
print('π Options:')
for i, size in enumerate(chunk_size_options):
print(f' Press {i} for {size // 1024} x 1024')
print('\nπ Press Enter for default (8 x 1024): \n')
chunk_size_input = input('π Your choice: ')
chunk_size = 1024 if chunk_size_input == '' else chunk_size_options[int(chunk_size_input)]
if chunk_size_input.isdigit() and int(chunk_size_input) in range(len(chunk_size_options)):
chunk_size = chunk_size_options[int(chunk_size_input)]
results = search_files(current_directory, keyword, context, True, chunk_size)
print(f'\nπ Results for keyword "{keyword}":')
directory = os.path.basename(os.path.abspath(os.curdir))
with open(f'xgrep-{keyword}-{directory}-{"".join(random.choices(string.digits, k=10))}.txt', 'w') as f:
for result in results:
print(f'π File: {result["file"]}')
print(f'π Match (surrounded by {context} characters of context):')
print(result['match'])
print()
f.write(f'File: {result["file"]}\n')
f.write(f'Match (surrounded by {context} characters of context):\n')
f.write(f'{result["match"]}\n\n')