Statistics.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import os
  2. import time
  3. import ID2TLib.libpcapreader as pr
  4. from ID2TLib.PcapFile import PcapFile
  5. from ID2TLib.StatsDatabase import StatsDatabase
  6. class Statistics:
  7. def __init__(self, pcap_file: PcapFile):
  8. """
  9. Creates a new Statistics object.
  10. :param pcap_file: A reference to the PcapFile object
  11. """
  12. # Fields
  13. self.pcap_filepath = pcap_file.pcap_file_path
  14. self.pcap_proc = None
  15. # Create folder for statistics database if required
  16. self.path_db = pcap_file.get_db_path()
  17. path_dir = os.path.dirname(self.path_db)
  18. if not os.path.isdir(path_dir):
  19. os.makedirs(path_dir)
  20. # Class instances
  21. self.stats_db = StatsDatabase(self.path_db)
  22. def load_pcap_statistics(self, flag_write_file: bool, flag_recalculate_stats: bool, flag_print_statistics: bool):
  23. """
  24. Loads the PCAP statistics for the file specified by pcap_filepath. If the database is not existing yet, the
  25. statistics are calculated by the PCAP file processor and saved into the newly created database. Otherwise the
  26. statistics are gathered directly from the existing database.
  27. :param flag_write_file: Indicates whether the statistics should be written addiotionally into a text file (True)
  28. or not (False)
  29. :param flag_recalculate_stats: Indicates whether eventually existing statistics should be recalculated
  30. :param flag_print_statistics: Indicates whether the gathered basic statistics should be printed to the terminal
  31. """
  32. # Load pcap and get loading time
  33. time_start = time.clock()
  34. # Inform user about recalculation of statistics and its reason
  35. if flag_recalculate_stats:
  36. print("Flag -r/--recalculate found. Recalculating statistics.")
  37. # Recalculate statistics if database not exists OR param -r/--recalculate was provided
  38. if (not self.stats_db.get_db_exists()) or flag_recalculate_stats:
  39. self.pcap_proc = pr.pcap_processor(self.pcap_filepath)
  40. self.pcap_proc.collect_statistics()
  41. self.pcap_proc.write_to_database(self.path_db)
  42. outstring_datasource = "by PCAP file processor."
  43. else:
  44. outstring_datasource = "from statistics database."
  45. # Load statistics from database
  46. self.file_info = self.stats_db.get_file_info()
  47. time_end = time.clock()
  48. print("Loaded file statistics in " + str(time_end - time_start)[:4] + " sec " + outstring_datasource)
  49. # Write statistics if param -e/--export provided
  50. if flag_write_file:
  51. self.write_statistics_to_file()
  52. # Print statistics if param -s/--statistics provided
  53. if flag_print_statistics:
  54. self.print_statistics()
  55. def get_file_information(self):
  56. """
  57. Returns a list of tuples, each containing a information of the file.
  58. :return: a list of tuples, each consisting of (description, value, unit), where unit is optional.
  59. """
  60. return [("Pcap file", self.pcap_filepath),
  61. ("#Packets", self.get_packet_count(), "packets"),
  62. ("Capture length", self.get_capture_duration(), "seconds"),
  63. ("Capture start", self.get_pcap_timestamp_start()),
  64. ("Capture end", self.get_pcap_timestamp_end())]
  65. def get_general_file_statistics(self):
  66. """
  67. Returns a list of tuples, each containing a file statistic.
  68. :return: a list of tuples, each consisting of (description, value, unit).
  69. """
  70. return [("Avg. packet rate", self.file_info['avgPacketRate'], "packets/sec"),
  71. ("Avg. packet size", self.file_info['avgPacketSize'], "kbytes"),
  72. ("Avg. packets sent", self.file_info['avgPacketsSentPerHost'], "packets"),
  73. ("Avg. bandwidth in", self.file_info['avgBandwidthIn'], "kbit/s"),
  74. ("Avg. bandwidth out", self.file_info['avgBandwidthOut'], "kbit/s")]
  75. @staticmethod
  76. def write_list(desc_val_unit_list, func, line_ending="\n"):
  77. """
  78. Takes a list of tuples (statistic name, statistic value, unit) as input, generates a string of these three values
  79. and applies the function func on this string.
  80. Before generating the string, it identifies text containing a float number, casts the string to a
  81. float and rounds the value to two decimal digits.
  82. :param desc_val_unit_list: The list of tuples consisting of (description, value, unit)
  83. :param func: The function to be applied to each generated string
  84. :param line_ending: The formatting string to be applied at the end of each string
  85. """
  86. for entry in desc_val_unit_list:
  87. # Convert text containing float into float
  88. (description, value) = entry[0:2]
  89. if isinstance(value, str) and "." in value:
  90. try:
  91. value = float(value)
  92. except ValueError:
  93. pass # do nothing -> value was not a float
  94. # round float
  95. if isinstance(value, float):
  96. value = round(value, 2)
  97. # write into file
  98. if len(entry) == 3:
  99. unit = entry[2]
  100. func(description + ":\t" + str(value) + " " + unit + line_ending)
  101. else:
  102. func(description + ":\t" + str(value) + line_ending)
  103. def print_statistics(self):
  104. """
  105. Prints the basic file statistics to the terminal.
  106. """
  107. print("\nPCAP FILE INFORMATION ------------------------------")
  108. Statistics.write_list(self.get_file_information(), print, "")
  109. print("\nGENERAL FILE STATISTICS ----------------------------")
  110. Statistics.write_list(self.get_general_file_statistics(), print, "")
  111. print("\n")
  112. def write_statistics_to_file(self):
  113. """
  114. Writes the calculated basic statistics into a file.
  115. """
  116. def _write_header(title: str):
  117. """
  118. Writes the section header into the open file.
  119. :param title: The section title
  120. """
  121. target.write("====================== \n")
  122. target.write(title + " \n")
  123. target.write("====================== \n")
  124. target = open(self.pcap_filepath + ".stat", 'w')
  125. target.truncate()
  126. _write_header("PCAP file information")
  127. Statistics.write_list(self.get_file_information(), target.write)
  128. _write_header("General statistics")
  129. Statistics.write_list(self.get_general_file_statistics(), target.write)
  130. target.close()
  131. def get_capture_duration(self):
  132. """
  133. :return: The duration of the capture in seconds
  134. """
  135. return self.file_info['captureDuration']
  136. def get_pcap_timestamp_start(self):
  137. """
  138. :return: The timestamp of the first packet in the PCAP file
  139. """
  140. return self.file_info['timestampFirstPacket']
  141. def get_pcap_timestamp_end(self):
  142. """
  143. :return: The timestamp of the last packet in the PCAP file
  144. """
  145. return self.file_info['timestampLastPacket']
  146. def get_pps_sent(self, ip_address: str):
  147. """
  148. Calculates the sent packets per seconds for a given IP address.
  149. :param ip_address: The IP address whose packets per second should be calculated
  150. :return: The sent packets per seconds for the given IP address
  151. """
  152. packets_sent = self.stats_db.process_db_query("SELECT pktsSent from ip_statistics WHERE ipAddress=?", False,
  153. (ip_address,))
  154. capture_duration = float(self.get_capture_duration())
  155. return int(float(packets_sent) / capture_duration)
  156. def get_packet_count(self):
  157. """
  158. :return: The number of packets in the loaded PCAP file
  159. """
  160. return self.file_info['packetCount']
  161. def get_statistics_database(self):
  162. """
  163. :return: A reference to the statistics database object
  164. """
  165. return self.stats_db
  166. def process_db_query(self, query_string_in: str, print_results: bool = False):
  167. """
  168. Executes a string identified previously as a query. This can be a standard SQL SELECT/INSERT query or a named
  169. query.
  170. :param query_string_in: The query to be processed
  171. :param print_results: Indicates whether the results should be printed to terminal
  172. :return: The result of the query
  173. """
  174. return self.stats_db.process_db_query(query_string_in, print_results)
  175. def is_query(self, value: str):
  176. """
  177. Checks whether the given string is a standard SQL query (SELECT, INSERT) or a named query.
  178. :param value: The string to be checked
  179. :return: True if the string is recognized as a query, otherwise False.
  180. """
  181. is_scalar_value = type(value) in (int, float)
  182. return not is_scalar_value and (
  183. any(x in value.lower().strip() for x in self.stats_db.get_all_named_query_keywords()) or
  184. any(x in value.lower().strip() for x in self.stats_db.get_all_sql_query_keywords()))