Simple Apache/HTTPD log parser for administrative analysis
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1067 lines
32 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. #!/bin/env python
  2. # Simple Apache HTTPD log file parser
  3. # Copyright (C) 2022 Pekka Helenius <pekka [dot] helenius [at] fjordtek [dot] com>
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. ################################################################
  18. # TODO: prev_host: instead of comparing to previous entry, check if such IP has been seen in XXX seconds
  19. # TODO: store IP values for temporary list for XXX seconds, and check list values
  20. # TODO: implement warning check for geoiplookup tool database files, i.e. "warning, some geo database files are very old. Please consider updating geo database information."
  21. import argparse
  22. import os
  23. import re
  24. import subprocess
  25. from datetime import datetime
  26. from apachelogs import LogParser, InvalidEntryError
  27. class text_processing(object):
  28. """
  29. Init
  30. """
  31. def __init__(self, verbose):
  32. self.show_verbose = verbose
  33. """
  34. Verbose output format (we do not use logger library)
  35. """
  36. def print_verbose(self, prefix='output', *args):
  37. if self.show_verbose:
  38. print('VERBOSE [{:s}]: {:s}'.format(prefix, ', '.join([str(i) for i in args])))
  39. class program(object):
  40. """
  41. Init
  42. """
  43. def __init__(self):
  44. self.args = self.get_args()
  45. # Exclude private IP address classes from geo lookup process
  46. # Strip out %I and %O flags from Apache log format
  47. # 127.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16
  48. self.private_class_ip_networks = ['^127\.', '^172\.(1[6-9]{1}|2[0-9]{1}|3[0-1]{1})\.', '^192\.168\.']
  49. self.txt = text_processing(verbose = self.args.verbose)
  50. """
  51. Define & get output fields
  52. """
  53. def get_out_fields(self):
  54. out_fields = {
  55. 'log_file_name': {'data': None, 'format': '{:s}', 'included': False, 'human_name': 'Log file name', 'sort_index': 0},
  56. 'http_status': {'data': None, 'format': '{:3s}', 'included': True, 'human_name': 'Status', 'sort_index': 1},
  57. 'remote_host': {'data': None, 'format': '{:15s}', 'included': True, 'human_name': 'Remote IP', 'sort_index': 2},
  58. 'country': {'data': None, 'format': '{:20s}', 'included': False, 'human_name': 'Country', 'sort_index': 3},
  59. 'city': {'data': None, 'format': '{:15s}', 'included': False, 'human_name': 'City', 'sort_index': 4},
  60. 'time': {'data': None, 'format': '{:20s}', 'included': True, 'human_name': 'Date/Time', 'sort_index': 5},
  61. 'time_diff': {'data': None, 'format': '{:8s}', 'included': True, 'human_name': 'Time diff', 'sort_index': 6},
  62. 'user_agent': {'data': None, 'format': '{:s}', 'included': True, 'human_name': 'User agent', 'sort_index': 7},
  63. 'http_request': {'data': None, 'format': '{:s}', 'included': True, 'human_name': 'Request', 'sort_index': 8}
  64. }
  65. return out_fields
  66. """
  67. Argument parser
  68. """
  69. def get_args(self):
  70. all_fields = self.get_out_fields()
  71. incl_fields = [i for i in all_fields.keys() if all_fields[i]['included']]
  72. out_time_format = "%d-%m-%Y %H:%M:%S"
  73. argparser = argparse.ArgumentParser(
  74. description = 'Apache HTTPD server log parser',
  75. formatter_class = argparse.ArgumentDefaultsHelpFormatter
  76. )
  77. argparser.add_argument(
  78. '-fr', '--files-regex',
  79. help = 'Apache log files matching input regular expression.',
  80. nargs = '?',
  81. dest = 'files_regex',
  82. required = False
  83. )
  84. argparser.add_argument(
  85. '-f', '--files-list',
  86. help = 'Apache log files.\nRegular expressions supported.',
  87. nargs = '?',
  88. type = lambda x: [i for i in x.split(',')],
  89. dest = 'files_list',
  90. required = False
  91. )
  92. argparser.add_argument(
  93. '-c', '--status-codes',
  94. help = 'Print only these numerical status codes.\nRegular expressions supported.',
  95. nargs = '+',
  96. dest = 'codes'
  97. )
  98. argparser.add_argument(
  99. '-cf', '--countries',
  100. help = 'Include only these countries.\nNegative match (exclude): "\!Country"',
  101. nargs = '?',
  102. type = lambda x: [i for i in x.split(',')],
  103. dest = 'countries'
  104. )
  105. argparser.add_argument(
  106. '-tf', '--time-format',
  107. help = 'Output time format.',
  108. nargs = '?',
  109. dest = 'time_format',
  110. default = out_time_format
  111. )
  112. argparser.add_argument(
  113. '-if', '--included-fields',
  114. help = 'Included fields.\nAll fields: all, ' + ', '.join(all_fields),
  115. nargs = '?',
  116. dest = 'incl_fields',
  117. type = lambda x: [i for i in x.split(',')],
  118. default = ','.join(incl_fields)
  119. )
  120. argparser.add_argument(
  121. '-ef', '--excluded-fields',
  122. help = 'Excluded fields.',
  123. nargs = '?',
  124. dest = 'excl_fields',
  125. type = lambda x: [i for i in x.split(',')],
  126. default = None
  127. )
  128. argparser.add_argument(
  129. '-gl', '--geo-location',
  130. help = 'Check origin countries with external "geoiplookup" tool.\nNOTE: Automatically includes "country" and "city" fields.',
  131. action = 'store_true',
  132. dest = 'use_geolocation'
  133. )
  134. argparser.add_argument(
  135. '-ge', '--geotool-exec',
  136. help = '"geoiplookup" tool executable found in PATH.',
  137. nargs = '?',
  138. dest = 'geotool_exec',
  139. default = "geoiplookup"
  140. )
  141. argparser.add_argument(
  142. '-gd', '--geo-database-dir',
  143. help = 'Database file directory for "geoiplookup" tool.',
  144. nargs = '?',
  145. dest = 'geo_database_location',
  146. default = '/usr/share/GeoIP/'
  147. )
  148. argparser.add_argument(
  149. '-dl', '--day-lower',
  150. help = 'Do not check log entries older than this day.\nDay syntax: 31-12-2020',
  151. nargs = '?',
  152. dest = 'date_lower'
  153. )
  154. argparser.add_argument(
  155. '-du', '--day-upper',
  156. help = 'Do not check log entries newer than this day.\nDay syntax: 31-12-2020',
  157. nargs = '?',
  158. dest = 'date_upper'
  159. )
  160. argparser.add_argument(
  161. '-sb', '--sort-by',
  162. help = 'Sort by an output field.',
  163. nargs = '?',
  164. dest = 'sortby_field'
  165. )
  166. argparser.add_argument(
  167. '-ro', '--reverse',
  168. help = 'Sort in reverse order.',
  169. dest = 'sortby_reverse',
  170. action = 'store_true'
  171. )
  172. argparser.add_argument(
  173. '-st', '--show-stats',
  174. help = 'Show short statistics at the end.',
  175. action = 'store_true',
  176. dest = 'show_stats'
  177. )
  178. argparser.add_argument(
  179. '-p', '--show-progress',
  180. help = 'Show progress information.',
  181. dest = 'show_progress',
  182. action = 'store_true'
  183. )
  184. argparser.add_argument(
  185. '--httpd-conf-file',
  186. help = 'Apache HTTPD configuration file with LogFormat directive.',
  187. action = 'store_true',
  188. dest = 'httpd_conf_file',
  189. default = '/etc/httpd/conf/httpd.conf'
  190. )
  191. argparser.add_argument(
  192. '--httpd-log-nickname',
  193. help = 'LogFormat directive nickname',
  194. action = 'store_true',
  195. dest = 'httpd_log_nickname',
  196. default = 'combinedio'
  197. )
  198. argparser.add_argument(
  199. '-lf', '--log-format',
  200. help = 'Log format, manually defined.',
  201. dest = 'log_format',
  202. required = False
  203. )
  204. argparser.add_argument(
  205. '-ph', '--print-header',
  206. help = 'Print column headers.',
  207. dest = 'column_headers',
  208. required = False,
  209. action = 'store_true'
  210. )
  211. argparser.add_argument(
  212. '--output-format',
  213. help = 'Output format for results.',
  214. dest = 'output_format',
  215. required = False,
  216. default = 'table',
  217. choices = ['table', 'csv']
  218. )
  219. argparser.add_argument(
  220. '--head',
  221. help = 'Read first N lines from all log entries.',
  222. dest = 'read_first_lines_num',
  223. required = False,
  224. nargs = '?',
  225. type = int
  226. )
  227. argparser.add_argument(
  228. '--tail',
  229. help = 'Read last N lines from all log entries.',
  230. dest = 'read_last_lines_num',
  231. required = False,
  232. nargs = '?',
  233. type = int
  234. )
  235. argparser.add_argument(
  236. '--sort-logs-by',
  237. help = 'Sorting order for input log files.',
  238. dest = 'sort_logs_by_info',
  239. required = False,
  240. default = 'name',
  241. choices = ['date', 'size', 'name']
  242. )
  243. argparser.add_argument(
  244. '--verbose',
  245. help = 'Verbose output.',
  246. dest = 'verbose',
  247. required = False,
  248. action = 'store_true'
  249. )
  250. args = argparser.parse_args()
  251. return args
  252. """
  253. Populate recognized HTTP status codes
  254. """
  255. def populate_status_codes(self):
  256. http_valid_codes = [
  257. '100-103',
  258. '200-208',
  259. '218'
  260. '226',
  261. '300-308',
  262. '400-431',
  263. '451',
  264. '500-511'
  265. ]
  266. codes = []
  267. for code in http_valid_codes:
  268. if len(code.split('-')) == 2:
  269. code_start = int(code.split('-')[0])
  270. code_end = int(code.split('-')[1])
  271. for i in range(code_start,code_end):
  272. codes.append(str(i))
  273. else:
  274. codes.append(code)
  275. return codes
  276. """
  277. Get valid HTTP status codes from user input
  278. """
  279. def get_input_status_codes(self, valid_codes, user_codes):
  280. codes = []
  281. for user_code in user_codes:
  282. user_code = str(user_code)
  283. validated = False
  284. code_appended = False
  285. for valid_code in valid_codes:
  286. if re.search(user_code, valid_code):
  287. validated = True
  288. code_appended = True
  289. codes.append((valid_code, validated))
  290. else:
  291. validated = False
  292. if not code_appended:
  293. codes.append((user_code, validated))
  294. self.txt.print_verbose('Available status codes', codes)
  295. return codes
  296. """
  297. Get log file list
  298. """
  299. def get_files(self, files_regex = None, files_list = None):
  300. files = []
  301. if files_regex is None and files_list is None:
  302. raise Exception("Either single file or regex file selection method is required.")
  303. if files_regex and files_list:
  304. raise Exception("Single file and regex file selection methods are mutually exclusive.")
  305. if files_regex:
  306. log_dir = '/'.join(files_regex.split('/')[:-1])
  307. file_part = files_regex.split('/')[-1]
  308. for lfile in os.listdir(log_dir):
  309. if os.path.isfile(log_dir + '/' + lfile):
  310. if re.match(file_part, lfile):
  311. files.append(log_dir + '/' + lfile)
  312. if files_list:
  313. for lfile in files_list:
  314. if os.path.isfile(lfile):
  315. files.append(lfile)
  316. if len(files) == 0:
  317. raise Exception("No matching files found.")
  318. files.sort()
  319. self.txt.print_verbose('Input files', files)
  320. return files
  321. """
  322. Common file checker
  323. """
  324. def check_file(self, sfile, flag, env = None):
  325. file_path = sfile
  326. if env is not None:
  327. for path in os.environ[env].split(os.pathsep):
  328. file_path = os.path.join(path, sfile)
  329. if os.path.isfile(file_path):
  330. break
  331. if os.access(file_path, eval(flag)):
  332. self.txt.print_verbose('File check', file_path, 'flags: ' + flag)
  333. return True
  334. return False
  335. """
  336. Get Apache HTTPD LogFormat directive syntax
  337. """
  338. def get_httpd_logformat_directive(self, cfile, tag = None):
  339. try:
  340. log_format = None
  341. self.txt.print_verbose('Apache configuration file', cfile)
  342. with open(cfile, 'r') as f:
  343. for line in f:
  344. if re.search('^[ ]+LogFormat ".*' + tag, line):
  345. r = re.search('^[ ]+LogFormat "(.*)(!?("))', line)
  346. log_format = r.groups()[0].replace('\\', '')
  347. break
  348. f.close()
  349. self.txt.print_verbose('Log format', log_format)
  350. return log_format
  351. except:
  352. raise Exception("Couldn't open Apache HTTPD configuration file.")
  353. """
  354. Geotool processing
  355. """
  356. def geotool_get_data(self, geotool_ok, geotool_exec, database_file, remote_host):
  357. host_country = None
  358. host_city = None
  359. if re.match('|'.join(self.private_class_ip_networks), remote_host):
  360. host_country = "Local"
  361. host_city = "Local"
  362. return {
  363. 'host_country': host_country,
  364. 'host_city': host_city
  365. }
  366. if geotool_ok:
  367. host_country_main = subprocess.check_output([geotool_exec,'-d', database_file, remote_host]).rstrip().decode()
  368. host_country_main = host_country_main.split('\n')
  369. try:
  370. host_country = host_country_main[0].split(', ')[1]
  371. except:
  372. if re.search("Address not found", host_country_main[0]):
  373. host_country = "Unknown"
  374. if len(host_country_main) > 1:
  375. try:
  376. host_city = host_country_main[1].split(', ')[4]
  377. if re.search("N/A", host_city):
  378. host_city = "Unknown: " + host_country_main[1].split(', ')[6] + ', ' + host_country_main[1].split(', ')[7]
  379. except:
  380. pass
  381. return {
  382. 'host_country': host_country,
  383. 'host_city': host_city
  384. }
  385. return None
  386. """
  387. Status code filter
  388. """
  389. def filter_status_code(self, status_codes, final_status):
  390. skip_line = True
  391. for status in status_codes:
  392. # Status consists of numerical status value (num) and validity boolean value (num_ok)
  393. if len(status) != 2:
  394. continue
  395. num, num_ok = status
  396. if num_ok:
  397. status = int(num)
  398. if status == final_status:
  399. skip_line = False
  400. break
  401. return skip_line
  402. """
  403. Country name filter
  404. """
  405. def filter_country(self, countries, host_country):
  406. skip_line = True
  407. for country in countries:
  408. if country[1] == "!":
  409. country = country[2:]
  410. if country.lower() == host_country.lower():
  411. skip_line = True
  412. break
  413. else:
  414. skip_line = False
  415. elif country.lower() == host_country.lower():
  416. skip_line = False
  417. break
  418. return skip_line
  419. """
  420. Get lines to be processed from input files and min/max input
  421. min and max work much like Unix tools 'head' and 'tail'
  422. Only a single value (min or max) is allowed
  423. """
  424. def get_file_lines_head_tail(self, sfiles, line_range_min = None, line_range_max = None, files_order = None):
  425. files_and_lines = {'files': [], 'lines_total': 0, 'range_min': 0, 'range_max': 0}
  426. files_tmp = []
  427. lines_count = 0
  428. line_start = 0
  429. line_end = 0
  430. if line_range_min and line_range_max:
  431. raise Exception("Either first or last line limit can be used, not both.")
  432. if files_order is None:
  433. raise Exception("Sorting order for input files missing.")
  434. if line_range_min is not None:
  435. if line_range_min < 0:
  436. line_range_min = None
  437. if line_range_max is not None:
  438. if line_range_max < 0:
  439. line_range_max = None
  440. for sfile in sfiles:
  441. try:
  442. with open(sfile, 'r') as f:
  443. line_count = len(list(f))
  444. f.close()
  445. files_tmp.append({
  446. 'file': str(sfile),
  447. 'modified_date': os.path.getmtime(sfile),
  448. 'size': os.path.getsize(sfile),
  449. 'line_count': line_count
  450. })
  451. except:
  452. raise Exception("Couldn't read input file " + sfile)
  453. if files_order == 'date':
  454. files_tmp.sort(key = lambda d: d['modified_date'])
  455. elif files_order == 'size':
  456. files_tmp.sort(key = lambda d: d['size'])
  457. elif files_order == 'name':
  458. files_tmp.sort(key = lambda d: d['file'])
  459. i = 0
  460. for sfile in files_tmp:
  461. line_end = (line_start + sfile['line_count']) - 1
  462. files_and_lines['files'].append({
  463. 'file': sfile['file'],
  464. 'line_start_global': line_start,
  465. 'line_end_global': line_end,
  466. 'line_start_local': 0,
  467. 'line_end_local': sfile['line_count'] - 1,
  468. })
  469. lines_count += line_count
  470. line_start = files_and_lines['files'][i]['line_end_global'] + 1
  471. i += 1
  472. range_line_start = files_and_lines['files'][0]['line_start_global']
  473. full_range = files_and_lines['files'][-1]['line_end_global']
  474. files_and_lines['range_min'] = range_line_start
  475. files_and_lines['range_max'] = full_range
  476. files_and_lines['lines_total'] = full_range - range_line_start
  477. i = 0
  478. # Read last N lines
  479. if line_range_max is not None:
  480. range_start = full_range - line_range_max
  481. if range_start <= 0:
  482. range_start = 0
  483. for l in files_and_lines['files']:
  484. if range_start >= l['line_start_global'] and range_start <= l['line_end_global']:
  485. l['line_start_global'] = range_start
  486. l['line_start_local'] = l['line_end_local'] - (l['line_end_global'] - range_start)
  487. del files_and_lines['files'][:i]
  488. i += 1
  489. # Read first N lines
  490. if line_range_min is not None:
  491. range_end = line_range_min
  492. if range_end >= full_range:
  493. range_end = full_range
  494. for l in files_and_lines['files']:
  495. if range_end >= l['line_start_global'] and range_end <= l['line_end_global']:
  496. l['line_end_local'] = l['line_end_local'] - l['line_start_local'] - (l['line_end_global'] - range_end)
  497. l['line_end_global'] = range_end
  498. del files_and_lines['files'][i + 1:]
  499. i += 1
  500. return files_and_lines
  501. """
  502. Get lines to be processed from input files and range input
  503. Range: <min> - <max>
  504. """
  505. def get_file_lines_range(self, sfiles, line_range_min=None, line_range_max=None):
  506. files_and_lines = {'files': [], 'lines_total': 0, 'range_min': 0, 'range_max': 0}
  507. lines_count = 0
  508. line_start = 0
  509. line_end = 0
  510. range_line_start = 0
  511. range_line_end = 0
  512. range_line_start_found = False
  513. if line_range_min is not None:
  514. if line_range_min < 0:
  515. line_range_min = None
  516. if line_range_max is not None:
  517. if line_range_max < 0:
  518. line_range_max = None
  519. for sfile in sfiles:
  520. append = False
  521. try:
  522. with open(sfile, 'r') as f:
  523. line_count = len(list(f))
  524. f.close()
  525. line_end = line_start + line_count
  526. if line_range_min is not None:
  527. if line_range_min >= line_start and line_range_min <= line_end:
  528. append = True
  529. line_start = line_range_min
  530. if line_range_min is None and line_end < line_range_max:
  531. append = True
  532. if line_range_max is not None:
  533. if line_range_max >= line_start and line_range_max <= line_end:
  534. append = True
  535. line_end = line_range_max
  536. if line_range_min < line_end and line_range_max > line_end:
  537. append = True
  538. if line_range_max is None and line_start > line_range_min:
  539. append = True
  540. if append:
  541. files_and_lines['files'].append({
  542. 'file': str(sfile),
  543. 'line_start_global': line_start,
  544. 'line_end_global': line_end,
  545. 'modified_date': os.path.getmtime(sfile),
  546. 'size': os.path.getsize(sfile)
  547. })
  548. # Use only the first matching line_start value
  549. if not range_line_start_found:
  550. range_line_start_found = True
  551. range_line_start = line_start
  552. # Use the last matching line_end value
  553. range_line_end = line_end
  554. lines_count += line_count
  555. line_start = lines_count + 1
  556. except:
  557. raise Exception("Couldn't read input file " + sfile)
  558. files_and_lines['lines_total'] = range_line_end - range_line_start
  559. files_and_lines['range_min'] = range_line_start
  560. files_and_lines['range_max'] = range_line_end
  561. return files_and_lines
  562. """
  563. Date checker
  564. """
  565. def date_checker(self, date_lower, date_upper, entry_time):
  566. # TODO Handle situations where date_upper & date_lower are equal
  567. if date_upper is not None and date_lower is not None:
  568. if date_lower > date_upper:
  569. raise Exception("Earlier day can't be later than later day")
  570. if date_upper is not None:
  571. if date_upper > datetime.now():
  572. raise Exception("Day can't be in the future")
  573. if date_lower is not None:
  574. if date_lower > datetime.now():
  575. raise Exception("Day can't be in the future")
  576. if date_lower is not None:
  577. if entry_time <= date_lower: return False
  578. if date_upper is not None:
  579. if entry_time >= date_upper: return False
  580. return True
  581. """
  582. Get output field definitions (sortby)
  583. """
  584. def get_out_field(self, fields, field_input):
  585. i = 0
  586. for field in fields:
  587. if field == field_input:
  588. return [True, i]
  589. i += 1
  590. return [False, i]
  591. """
  592. Get included fields
  593. """
  594. def get_included_fields(self, fields, included_fields, excluded_fields=None):
  595. if included_fields:
  596. # TODO: simplify logic
  597. n = 0
  598. included_fields = [[i.replace(' ',''), 0] for i in included_fields]
  599. for a in included_fields:
  600. a[1] += n
  601. n += 1
  602. if excluded_fields:
  603. excluded_fields = [i.replace(' ','') for i in excluded_fields]
  604. all_defined_fields = []
  605. fields_out = {}
  606. if 'all' in included_fields or included_fields is None:
  607. included_fields = [[i, int(i['sort_index'])] for i in fields.keys()]
  608. if excluded_fields is not None:
  609. if 'all' in excluded_fields:
  610. raise Exception("No output fields defined.")
  611. # TODO: simplify logic
  612. n = 0
  613. included_fields = [[i, 0] for i in included_fields if i not in excluded_fields]
  614. for a in included_fields:
  615. a[1] += n
  616. n += 1
  617. all_defined_fields = [i[0] for i in included_fields] + excluded_fields
  618. else:
  619. all_defined_fields = included_fields
  620. for i in all_defined_fields:
  621. if i[0] not in fields.keys():
  622. raise Exception("Unknown field value: {}. Accepted values: {}".format(i, ','.join(fields.keys())))
  623. for a in included_fields:
  624. for key, value in fields.items():
  625. if key == a[0]:
  626. value['sort_index'] = a[1]
  627. value['included'] = True
  628. fields_out[key] = value
  629. if len(fields_out.keys()) == 0:
  630. raise Exception("No output fields defined.")
  631. return fields_out
  632. """
  633. Process input files
  634. """
  635. def process_files(self):
  636. prev_host = ""
  637. log_entries = []
  638. codes = []
  639. countries = []
  640. # Log format as defined in Apache/HTTPD configuration file (LogFormat directive) or manually by user
  641. if self.args.log_format:
  642. log_format = self.args.log_format
  643. else:
  644. log_format = self.get_httpd_logformat_directive(self.args.httpd_conf_file, self.args.httpd_log_nickname)
  645. # Remove bytes in & out fields from local traffic pattern
  646. log_format_local = log_format.replace('%I','').replace('%O','').strip()
  647. parser = LogParser(log_format)
  648. parser_local = LogParser(log_format_local)
  649. if self.args.codes:
  650. codes = self.get_input_status_codes(self.populate_status_codes(), self.args.codes)
  651. if self.args.countries:
  652. countries = self.args.countries
  653. date_lower = self.args.date_lower
  654. date_upper = self.args.date_upper
  655. day_format = "%d-%m-%Y"
  656. if date_lower is not None:
  657. date_lower = datetime.strptime(date_lower, day_format)
  658. if date_upper is not None:
  659. date_upper = datetime.strptime(date_upper, day_format)
  660. geotool_exec = self.args.geotool_exec
  661. geo_database_location = self.args.geo_database_location
  662. incl_fields = self.args.incl_fields
  663. if isinstance(self.args.incl_fields, str):
  664. incl_fields = self.args.incl_fields.split(',')
  665. use_geolocation = self.args.use_geolocation
  666. geotool_ok = False
  667. if use_geolocation:
  668. if self.check_file(geotool_exec, "os.X_OK", "PATH") and self.check_file(geo_database_location, "os.R_OK"):
  669. geotool_ok = True
  670. if use_geolocation:
  671. if 'country' not in incl_fields:
  672. incl_fields.append('country')
  673. if 'city' not in incl_fields:
  674. incl_fields.append('city')
  675. if 'country' in incl_fields or 'city' in incl_fields:
  676. use_geolocation = True
  677. fields = self.get_included_fields(
  678. self.get_out_fields(),
  679. incl_fields,
  680. self.args.excl_fields
  681. )
  682. invalid_lines = []
  683. field_names = []
  684. country_seen = False
  685. geo_data = None
  686. skip_line_by_status = False
  687. skip_line_by_country = False
  688. file_num = 0
  689. stri = ""
  690. files_input = self.get_files(self.args.files_regex, self.args.files_list)
  691. files_process_data = self.get_file_lines_head_tail(
  692. files_input,
  693. self.args.read_first_lines_num,
  694. self.args.read_last_lines_num,
  695. self.args.sort_logs_by_info
  696. )
  697. lines_total = files_process_data['lines_total']
  698. files_total = len(files_process_data['files'])
  699. self.txt.print_verbose(
  700. 'Log entry range',
  701. str(files_process_data['files'][0]['line_start_global'])
  702. + ' - ' +
  703. str(files_process_data['files'][-1]['line_end_global'])
  704. )
  705. if self.args.show_progress or self.args.verbose:
  706. print(
  707. "File count: {}\nLines in total: {}".format(
  708. str(files_total),
  709. str(lines_total)
  710. ))
  711. for lfile in files_process_data['files']:
  712. if self.args.show_progress or self.args.verbose:
  713. print("Processing file: {:s} (lines: {:d}-{:d})".format(
  714. lfile['file'],
  715. lfile['line_start_global'], lfile['line_end_global']
  716. ))
  717. with open(lfile['file'], 'r') as f:
  718. f = list(f)
  719. range_start = files_process_data['files'][file_num]['line_start_local']
  720. range_end = files_process_data['files'][file_num]['line_end_local']
  721. lines = range(range_start, range_end)
  722. line_num = 1
  723. for line in lines:
  724. if self.args.show_progress or self.args.verbose:
  725. print("Processing log entry: {:d}/{:d} ({}%)".format(
  726. line_num,
  727. len(lines),
  728. round(100 * (line_num/len(lines)), 2)
  729. ), end = "\r")
  730. if line_num != 1 and not (skip_line_by_status or skip_line_by_country) and entry_data:
  731. prev_host = entry_data['remote_host']
  732. prev_host_time = entry_data['time']
  733. try:
  734. if re.match('|'.join(self.private_class_ip_networks), f[line]):
  735. entry = parser_local.parse(f[line])
  736. else:
  737. entry = parser.parse(f[line])
  738. except InvalidEntryError:
  739. invalid_lines.append((lfile['file'], line_num))
  740. line_num += 1
  741. continue
  742. entry_data = {
  743. 'time': entry.request_time.replace(tzinfo = None),
  744. 'user_agent': entry.headers_in["User-Agent"],
  745. 'http_request': str(entry.request_line).encode('unicode_escape').decode(),
  746. 'remote_host': entry.remote_host,
  747. 'status': entry.final_status
  748. }
  749. if not self.date_checker(date_lower, date_upper, entry_data['time']):
  750. line_num += 1
  751. continue
  752. if len(codes) > 0:
  753. skip_line_by_status = self.filter_status_code(codes, entry_data['status'])
  754. if use_geolocation:
  755. if prev_host == entry_data['remote_host']:
  756. country_seen = True
  757. else:
  758. country_seen = False
  759. if not country_seen:
  760. geo_data = self.geotool_get_data(geotool_ok, geotool_exec, geo_database_location, entry_data['remote_host'])
  761. if len(countries) > 0 and geo_data is not None:
  762. skip_line_by_country = self.filter_country(countries, geo_data['host_country'])
  763. else:
  764. skip_line_by_country = False
  765. if skip_line_by_status or skip_line_by_country:
  766. line_num += 1
  767. continue
  768. time_diff = str('NEW_CONN')
  769. if prev_host == entry_data['remote_host']:
  770. time_diff = (entry_data['time'] - prev_host_time).total_seconds()
  771. if isinstance(time_diff, float):
  772. time_diff = int(time_diff)
  773. if time_diff > 0:
  774. time_diff = "+" + str(time_diff)
  775. if line_num == 1 and file_num == 0:
  776. time_diff = int(0)
  777. if 'log_file_name' in fields:
  778. fields['log_file_name']['data'] = lfile
  779. if 'http_status' in fields:
  780. fields['http_status']['data'] = entry_data['status']
  781. if 'remote_host' in fields:
  782. fields['remote_host']['data'] = entry_data['remote_host']
  783. if geo_data is not None:
  784. if 'country' in fields:
  785. fields['country']['data'] = geo_data['host_country']
  786. if 'city' in fields:
  787. fields['city']['data'] = geo_data['host_city']
  788. if 'time' in fields:
  789. fields['time']['data'] = entry_data['time']
  790. if 'time_diff' in fields:
  791. fields['time_diff']['data'] = time_diff
  792. if 'user_agent' in fields:
  793. fields['user_agent']['data'] = entry_data['user_agent']
  794. if 'http_request' in fields:
  795. fields['http_request']['data'] = entry_data['http_request']
  796. stri = ""
  797. printargs = []
  798. for key, value in fields.items():
  799. if not use_geolocation and (key == 'country' or key == 'city'):
  800. continue
  801. if value['included']:
  802. stri += "\t" + value['format']
  803. printargs.append(value['data'])
  804. if not any(key in i for i in field_names):
  805. field_names.append((key, value['human_name']))
  806. log_entries.append(printargs)
  807. line_num += 1
  808. file_num += 1
  809. return [log_entries, files_process_data['files'], lines_total, stri, field_names, invalid_lines]
  810. """
  811. Execute
  812. """
  813. def execute(self):
  814. print_headers = self.args.column_headers
  815. show_progress = self.args.show_progress
  816. show_stats = self.args.show_stats
  817. output_format = self.args.output_format
  818. sortby_field = self.args.sortby_field
  819. reverse_order = self.args.sortby_reverse
  820. if self.args.incl_fields:
  821. if 'all' not in self.args.incl_fields:
  822. if sortby_field and sortby_field not in self.args.incl_fields:
  823. raise Exception("Sort-by field must be included in output fields.")
  824. results = self.process_files()
  825. result_entries = results[0]
  826. result_files = results[1]
  827. result_lines = results[2]
  828. stri = results[3]
  829. out_fields = [i[0] for i in results[4]]
  830. out_fields_human_names = [i[1] for i in results[4]]
  831. invalid_lines = results[5]
  832. if sortby_field is None and reverse_order:
  833. raise Exception("You must define a field for reverse sorting.")
  834. if sortby_field is not None:
  835. out_field_validation = self.get_out_field(out_fields, sortby_field)
  836. if out_field_validation[0]:
  837. result_entries.sort(
  838. key = lambda r : r[out_field_validation[1]] or '',
  839. reverse = reverse_order
  840. )
  841. if output_format == 'table':
  842. if print_headers:
  843. print("\n")
  844. print(stri.format(*out_fields_human_names).lstrip())
  845. for entry in result_entries:
  846. c = 0
  847. entry_items = []
  848. while c < len(entry):
  849. entry_items.append(str(entry[c]))
  850. c += 1
  851. print(stri.format(*entry_items).lstrip())
  852. if output_format == 'csv':
  853. if print_headers:
  854. print(','.join(out_fields_human_names))
  855. for entry in result_entries:
  856. c = 0
  857. entry_items = []
  858. while c < len(entry):
  859. entry_items.append(str(entry[c]))
  860. c += 1
  861. print(','.join(entry_items))
  862. if show_stats:
  863. print(("\n" +
  864. "Processed files: {:s}\n" +
  865. "Processed log entries: {:d}\n" +
  866. "Matched log entries: {:d}\n"
  867. ).format(
  868. ', '.join([i['file'] for i in result_files['files']]),
  869. result_lines,
  870. len(result_entries)
  871. )
  872. )
  873. if len(invalid_lines) > 0:
  874. print("Invalid lines:")
  875. for i in invalid_lines:
  876. print("\tFile: {:s}, line: {:d}".format(i[0], i[1]))
  877. print("\n")
  878. if __name__ == "__main__":
  879. app = program()
  880. app.execute()