forked from TheDreamPort/deep_exploit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCreateReport.py
More file actions
180 lines (155 loc) · 8.05 KB
/
CreateReport.py
File metadata and controls
180 lines (155 loc) · 8.05 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
#!/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import codecs
import glob
import configparser
import pandas as pd
from datetime import datetime
from docopt import docopt
from jinja2 import Environment, FileSystemLoader
from util import Utilty
# Type of printing.
OK = 'ok' # [*]
NOTE = 'note' # [+]
FAIL = 'fail' # [-]
WARNING = 'warn' # [!]
NONE = 'none' # No label.
# Create report.
class CreateReport:
def __init__(self):
self.util = Utilty()
# Read config file.
full_path = os.path.dirname(os.path.abspath(__file__))
config = configparser.ConfigParser()
try:
config.read(os.path.join(full_path, 'config.ini'))
except Exception as err:
self.util.print_exception(err, 'File exists error')
sys.exit(1)
self.report_date_format = config['Report']['date_format']
self.report_test_path = os.path.join(full_path, config['Report']['report_test'])
self.report_test_file = os.path.join(self.report_test_path, config['Report']['report_test_file'])
self.template_test = config['Report']['template_test']
self.report_train_path = os.path.join(self.report_test_path, config['Report']['report_train'])
self.report_train_file = os.path.join(self.report_train_path, config['Report']['report_train_file'])
self.template_train = config['Report']['template_train']
self.header_train = str(config['Report']['header_train']).split('@')
self.header_test = str(config['Report']['header_test']).split('@')
def create_report(self, mode='train', start_date=None):
# Check mode.
if mode not in ['train', 'test']:
self.util.print_message(FAIL, 'Invalid mode: {}'.format(mode))
exit(1)
# Gather reporting items.
if mode == 'train':
self.util.print_message(NOTE, 'Creating training report.')
csv_file_list = glob.glob(os.path.join(self.report_train_path, '*.csv'))
# Create DataFrame.
content_list = []
for file in csv_file_list:
df = pd.read_csv(file, names=self.header_train, sep=',')
df['date'] = pd.to_datetime(df['date'])
selected_df = df[(start_date < df['date'])]
content_list.append(selected_df)
if len(content_list) != 0:
df_csv = pd.concat(content_list).drop_duplicates().sort_values(by=['ip', 'port'],
ascending=True).reset_index(drop=True,
col_level=1)
items = []
for idx in range(len(df_csv)):
items.append({'ip_addr': df_csv.loc[idx, 'ip'],
'port': df_csv.loc[idx, 'port'],
'prod_name': df_csv.loc[idx, 'service'],
'vuln_name': df_csv.loc[idx, 'vuln_name'],
'description': df_csv.loc[idx, 'description'],
'type': df_csv.loc[idx, 'type'],
'exploit': df_csv.loc[idx, 'exploit'],
'target': df_csv.loc[idx, 'target'],
'payload': df_csv.loc[idx, 'payload'],
'ref': str(df_csv.loc[idx, 'reference']).replace('@', '<br>')})
try:
# Setting template.
env = Environment(loader=FileSystemLoader(self.report_train_path))
template = env.get_template(self.template_train)
pd.set_option('display.max_colwidth', -1)
html = template.render({'title': 'Deep Exploit Scan Report', 'items': items})
# Write report.
with codecs.open(self.report_train_file, 'w', 'utf-8') as fout:
fout.write(html)
except Exception as err:
self.util.print_exception(err, 'Creating report error.')
else:
self.util.print_message(WARNING, 'Exploitation result is not found.')
self.util.print_message(OK, 'Creating training report done.')
else:
self.util.print_message(NOTE, 'Creating testing report.')
csv_file_list = glob.glob(os.path.join(self.report_test_path, '*.csv'))
# Create DataFrame.
content_list = []
for file in csv_file_list:
df = pd.read_csv(file, names=self.header_test, sep=',')
df['date'] = pd.to_datetime(df['date'])
selected_df = df[(start_date < df['date'])]
content_list.append(selected_df)
if len(content_list) != 0:
df_csv = pd.concat(content_list).drop_duplicates().sort_values(by=['ip', 'port'],
ascending=True).reset_index(drop=True,
col_level=1)
items = []
for idx in range(len(df_csv)):
items.append({'ip_addr': df_csv.loc[idx, 'ip'],
'port': df_csv.loc[idx, 'port'],
'source_ip_addr': df_csv.loc[idx, 'src_ip'],
'prod_name': df_csv.loc[idx, 'service'],
'vuln_name': df_csv.loc[idx, 'vuln_name'],
'description': df_csv.loc[idx, 'description'],
'type': df_csv.loc[idx, 'type'],
'exploit': df_csv.loc[idx, 'exploit'],
'target': df_csv.loc[idx, 'target'],
'payload': df_csv.loc[idx, 'payload'],
'ref': str(df_csv.loc[idx, 'reference']).replace('@', '<br>')})
try:
# Setting template.
env = Environment(loader=FileSystemLoader(self.report_test_path))
template = env.get_template(self.template_test)
pd.set_option('display.max_colwidth', -1)
html = template.render({'title': 'Deep Exploit Scan Report', 'items': items})
# Write report.
with codecs.open(self.report_test_file, 'w', 'utf-8') as fout:
fout.write(html)
except Exception as err:
self.util.print_exception(err, 'Creating report error.')
else:
self.util.print_message(WARNING, 'Exploitation result is not found.')
self.util.print_message(OK, 'Creating testing report done.')
# Define command option.
__doc__ = """{f}
Usage:
{f} (-m <mode> | --mode <mode>) [(-s <start> | --start <start>)]
{f} -h | --help
Options:
-m --mode Require : Creating mode "train/test".
-s --start Optional : begining start time (format='%Y%m%d%H%M%S')
-h --help Optional : Show this screen and exit.
""".format(f=__file__)
# Parse command arguments.
def command_parse():
args = docopt(__doc__)
mode = args['<mode>']
start_time = args['<start>']
return mode, start_time
if __name__ == '__main__':
# Get command arguments.
mode, start_time = command_parse()
# Create report.
report = CreateReport()
try:
if start_time is None:
start_time = '19000101000000'
get_date = datetime.strptime(start_time, '%Y%m%d%H%M%S')
report.create_report(mode, pd.to_datetime(report.util.transform_date_string(get_date)))
except Exception as err:
report.util.print_exception(err, 'Invalid date format: {}.'.format(start_time))
exit(1)