-
Notifications
You must be signed in to change notification settings - Fork 0
/
segrep
executable file
·177 lines (144 loc) · 6.04 KB
/
segrep
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
#!/usr/bin/env python3
# coding:utf8
import argparse
import linecache
import os
import re
from os.path import join, basename
file_count = 0
line_count = 0
'''
todo:
'''
# $ANDROID_BUILD_TOP='/disk01/work/work_berg/COSHIP_X1_5_0_last'
android_build_top = os.getenv('ANDROID_BUILD_TOP')
SEPOLICY_DIRS = [android_build_top + "/device/qcom/sepolicy/common/", android_build_top + "/external/sepolicy/",
android_build_top + "/external/tios_sepolicy/",android_build_top + "/external/tios_sepolicy/H1OPEN"]
sepolicy_build_files = ['attributes', "security_classes", "access_vectors",
'mls', 'roles', 'users',
"initial_sids",
'policy_capabilities',
'fs_use',
'te_macros', "global_macros", 'mls_macros',
'file_contexts', 'genfs_contexts', 'initial_sid_contexts', 'port_contexts', 'service_contexts',
'tios_macros',
'*.te']
matched_count = 0
and_flag = True #
words = list()
sepolicy_dirs = list()
flag_match_word = True
num_before = 0
num_after = 0
###################################################################################
class colors:
''' Class used to set console colors '''
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
@classmethod
def disable(cls):
cls.HEADER = ''
cls.OKBLUE = ''
cls.OKGREEN = ''
cls.WARNING = ''
cls.FAIL = ''
cls.ENDC = ''
def whole_match(words, line):
# line_words = re.findall('\w+', line)
pattern = re.compile('[a-zA-Z0-9-_]+')
line_words = re.findall(pattern, line)
if (not and_flag) and any((w for w in words if w in line_words)):
return True
if and_flag and all([w in line_words for w in words]):
return True
return False
def part_match(words, line):
if (not and_flag) and any((w in line for w in words)):
return True
if and_flag and all([w in line for w in words]):
return True
return False
_dis_index=0
def display_file(file_name, matched_lines, max_num, num_before, num_after):
# 将同一个文件中,所有匹配的行,以及要求显示的上下邻近行,一次性显示,。
# 需要显示的所有的行,set 遍历整数时是有序的
global _dis_index
_dis_index=(_dis_index+1)%2
line_nums = set()
# 计算所有的行
for num in matched_lines:
line_nums = line_nums.union(
filter(lambda n: 0 <= n <= max_num, range(num - num_before, num + num_after + 1)))
for num in line_nums:
line = linecache.getline(file_name, num).rstrip()
header_color = (colors.OKBLUE,colors.OKGREEN)[_dis_index]
if num in matched_lines:
for word in words:
line = line.replace(word, colors.FAIL + word + colors.ENDC)
header_color = (colors.HEADER,colors.WARNING)[_dis_index]
print("{} ({}):{}".format(header_color + basename(file_name) + colors.ENDC, num, line))
#print("\n")
def grep_func(file_name):
global and_flag
global words
global matched_count
global line_count
global file_count
file_count += + 1
matched_lines = []
for num, line in enumerate(linecache.getlines(file_name), 1):
line = line.strip()
if not line: continue
if not line.startswith("#"):
line_count += 1
# print line
if line.startswith("#") and not line.startswith("##"):
continue
matched = whole_match(words, line) if flag_match_word else part_match(words, line)
if matched:
matched_lines.append(num)
matched_count += 1
max_num = num
if matched_lines:
display_file(file_name,matched_lines,max_num,num_before,num_after)
##########################################################################
if __name__ == '__main__':
myParser = argparse.ArgumentParser(description='在策略中查找关键字')
myParser.add_argument('words', metavar='word', type=str, nargs='+', help='words list to search')
myParser.add_argument('--or', action='store_false', dest="and_flag", default=True, help="或运算")
myParser.add_argument('--and', action='store_true', dest="and_flag", help="与运算")
myParser.add_argument('--here', action="store_true", default=False, help="仅搜索当前目录")
myParser.add_argument('--part', action="store_false", default=True, help="部分匹配,默认为整字匹配")
myParser.add_argument('-A', '--after', action="store", default=0, type=int,
help="Print NUM lines of trailing context after matching lines.")
myParser.add_argument('-B', '--before', action="store", default=0, type=int,
help="Print NUM lines of leading context before matching lines.")
myParser.add_argument('-C', '--context', action="store", default=0, type=int,
help="Print NUM lines of output context.")
args = myParser.parse_args()
# print args
and_flag = args.and_flag
words = args.words
sepolicy_dirs = SEPOLICY_DIRS if not args.here else [os.path.abspath(os.path.curdir)]
num_before = max(args.before, args.context)
num_after = max(args.after, args.context)
flag_match_word = args.part
print("dirs=", sepolicy_dirs)
for sepolicy_dir in sepolicy_dirs:
# print "walking",sepolicy_dir
for root, dirs, files in os.walk(sepolicy_dir, topdown=True):
# skip all subdirs
if root != sepolicy_dir: continue
# print "root={} dirs={} files={}".format(root,dirs,files)
print("-" * 20)
print("root=", root)
for file in files:
if file in sepolicy_build_files or file.endswith(".te"):
# print join(root,file)
grep_func(join(root, file))
print("file_count={},line_count={},matched={}", file_count,line_count,matched_count)
print("done!")