Skip to content

Commit 852a3ba

Browse files
author
H.L.J.Laloge
committed
feat: add JSON output
1 parent 77bc447 commit 852a3ba

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

main.py

+26-11
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,26 @@
11
#!/usr/bin/env python3
22

33
import argparse
4+
import sys
5+
import json
46

5-
from polydet import magic, scan, rules
7+
from polydet import magic, scan, rules, PolyglotLevel
68

79

8-
def display_results(results: [(str, {})], indent=False):
9-
for result in results.items():
10-
if indent:
11-
print('\t', end='')
12-
print('%s: %s' % (result[0], result[1]))
10+
class PolyglotLevelEncoder(json.JSONEncoder):
11+
def default(self, o):
12+
if isinstance(o, PolyglotLevel):
13+
return {
14+
'isValid': o.is_valid,
15+
'suspiciousChunks': o.suspicious_chunks,
16+
'embedded': sorted(o.embedded)
17+
}
18+
19+
return super().default(o)
20+
21+
22+
def display_results(results: {str: {str: PolyglotLevel}}, fp):
23+
json.dump(results, fp, cls=PolyglotLevelEncoder)
1324

1425

1526
def create_arg_parser():
@@ -22,6 +33,7 @@ def create_arg_parser():
2233
arg_parser.add_argument('-r', '--rules', dest='rules', type=str, help='File to load and store rules to speed up the process.')
2334
arg_parser.add_argument('-c', '--recompile', dest='recompile', action='store_true', help='Re-compile rules. '
2435
'Require --rules')
36+
arg_parser.add_argument('-o', '--output', default='-', help='Output file')
2537
return arg_parser
2638

2739

@@ -39,12 +51,15 @@ def main():
3951
else:
4052
rules.load_or_compile(args.rules)
4153

42-
if len(args.files) == 1:
43-
display_results(scan(args.files[0], use_magic=args.magic))
54+
results = dict()
55+
for filename in args.files:
56+
results[filename] = scan(filename, use_magic=args.magic)
57+
58+
if args.output != '-':
59+
with open(args.output) as output:
60+
display_results(results, output)
4461
else:
45-
for filename in args.files:
46-
print('%s:' % filename)
47-
display_results(scan(filename, use_magic=args.magic), indent=True)
62+
display_results(results, sys.stdout)
4863

4964

5065
if __name__ == '__main__':

polydet/polyglot_level.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
class PolyglotLevel:
22

3-
def __init__(self, is_valid = True, suspicious_chunks: [(int, int)] = None, embedded: set = None):
3+
__slots__ = ['is_valid', 'suspicious_chunks', 'embedded']
4+
5+
def __init__(self, is_valid=True, suspicious_chunks: [(int, int)] = None, embedded: set = None):
46
self.is_valid = is_valid
57
self.suspicious_chunks = suspicious_chunks if suspicious_chunks is not None else []
68
self.embedded = embedded if embedded is not None else set()

0 commit comments

Comments
 (0)