main.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. import csv
  2. import os
  3. import sys
  4. import argparse
  5. from logger import *
  6. from datetime import datetime
  7. ARGS = None
  8. parse = argparse.ArgumentParser(
  9. description="Программа для сбора информации из csv файлов")
  10. parse.add_argument('-p', '--path', help='Указать в какой директории искать',
  11. default=os.path.dirname(sys.argv[0]))
  12. parse.add_argument('-e', '--encoding',
  13. help='Указать в какой кодировке сохранять', default='ANSI')
  14. parse.add_argument('-s', '--open_encoding',
  15. help='Указать в какой кодировке открывать', default='utf-16')
  16. parse.add_argument('-d', '--delimiter', help='разделитель csv', default=',')
  17. LIST_BAD_ADAPTER = ['Wireless', 'Bluetooth', 'Wireless', 'WiFi',
  18. 'Kaspersky', 'VirtualBox', 'TAP-Windows',
  19. 'Wintun', '802.11', 'VMware', 'VPN', 'Wi-Fi',
  20. '1394', 'Mobile']
  21. # Количетсво интерфейсов по умолчанию
  22. COUNT_INTERFACE = 1
  23. def check_correct_controller(name) -> bool:
  24. return any(ext not in name for ext in LIST_BAD_ADAPTER)
  25. class ObjectReady:
  26. frame: str = None
  27. cabinet: str = None
  28. os: str = None
  29. cpu: str = None
  30. ram: str = None
  31. motherboard: str = None
  32. count_interface: int = 0
  33. path: str = None
  34. def get_len_dict(self) -> int:
  35. return len(self.__dict__)
  36. def get_csv_row(self) -> str:
  37. if self.get_len_dict() < 11:
  38. return F"{ARGS.delimiter}".join((self.frame, self.cabinet))
  39. try:
  40. row_interface = F"{ARGS.delimiter}".join(
  41. [ARGS.delimiter.join(
  42. (self.__dict__.get(F"ip{i}"), self.__dict__.get(F"mac{i}")
  43. )
  44. ) for i in range(self.count_interface)])
  45. return ARGS.delimiter.join((self.frame, self.cabinet, self.os, self.motherboard, self.cpu, self.ram, row_interface))
  46. except AttributeError:
  47. return None
  48. def get_paths() -> list:
  49. list_path = []
  50. for root, _, files in os.walk(ARGS.path):
  51. list_path += [
  52. F"{root}/{file}" for file in files if file.split('.')[-1] == 'csv' and "result" not in file]
  53. return list_path
  54. def convert_mb_to_gb(val: str) -> str:
  55. numbers = int(''.join([x for x in val if x.isdigit()]))
  56. return str(round(numbers/1024, 1))+' GB'
  57. def get_ser_motherboard(row: str) -> str:
  58. if len(row) > 0:
  59. if row[6] not in ['To be filled by O.E.M.', 'Default string']:
  60. return row[6]
  61. else:
  62. return None
  63. else:
  64. return None
  65. def get_data_from_file(path: str, obj: ObjectReady) -> None:
  66. global COUNT_INTERFACE
  67. with open(path, 'r', encoding=ARGS.open_encoding) as file:
  68. cs = csv.reader(file, delimiter=',')
  69. next(cs)
  70. line_info_computers = next(cs)
  71. obj.os = line_info_computers[7]
  72. obj.cpu = line_info_computers[13]
  73. obj.ram = convert_mb_to_gb(line_info_computers[14])
  74. obj.ip1 = None
  75. obj.mac1 = None
  76. count_interface = 0
  77. for x in cs:
  78. if x[0] == '6200':
  79. obj.motherboard = get_ser_motherboard(x)
  80. if x[0] == '2600' and len(x) > 2 and check_correct_controller(x[3]):
  81. setattr(obj, F'ip{count_interface}', x[6].split(' ')[0])
  82. setattr(obj, F'mac{count_interface}', x[-3])
  83. count_interface += 1
  84. # Увеличиваем значение если количестов интерфейсов больше в этой строке
  85. obj.count_interface = count_interface
  86. if count_interface > COUNT_INTERFACE:
  87. COUNT_INTERFACE = count_interface
  88. file.close()
  89. def get_ready_information() -> list[ObjectReady]:
  90. list_objects = []
  91. for path in get_paths():
  92. obj = ObjectReady()
  93. obj.frame = os.path.basename(os.path.dirname(path))
  94. obj.path = path
  95. try:
  96. obj.cabinet = str(os.path.basename(path)).split('.')[0]
  97. except IndexError as er:
  98. logger.error(F"index error path: {path}")
  99. continue
  100. try:
  101. get_data_from_file(path, obj)
  102. logger.info(F'Parse success file: {path}')
  103. except UnicodeDecodeError as ude:
  104. logger.error(F"{path} --> {ude}")
  105. except UnicodeError as er:
  106. logger.error(F"{path} --> {er}")
  107. except StopIteration:
  108. logger.error(F"{path} --> Пустой файл или тмпо того")
  109. list_objects.append(obj)
  110. return list_objects
  111. def create_header_interface() -> str:
  112. return ARGS.delimiter.join([
  113. ARGS.delimiter.join((F"ip{i+1}", F"mac{i+1}"))
  114. for i in range(COUNT_INTERFACE)
  115. ])
  116. def create_csv(list_obj: list[ObjectReady]) -> None:
  117. namefile = F"result-{datetime.today().strftime('%Y-%m-%d-%H.%M.%S')}"
  118. with open(F"{namefile}.csv", 'w', newline='', encoding=ARGS.encoding) as f:
  119. header_interface = create_header_interface()
  120. header_csv = ARGS.delimiter.join(
  121. ("frame", "cabinet", "os", "motherboard", "cpu", "ram", header_interface))
  122. f.write(header_csv + "\n")
  123. for obj in list_obj:
  124. try:
  125. f.write(obj.get_csv_row() + '\n')
  126. except TypeError as te:
  127. logger.error(F'{obj.path} -> {te}')
  128. continue
  129. if __name__ == '__main__':
  130. logger.info("Start programm")
  131. try:
  132. ARGS = parse.parse_args(sys.argv[1:])
  133. except argparse.ArgumentError:
  134. parse.print_help()
  135. create_logger()
  136. logger.info(F"Base dir: {ARGS.path}")
  137. create_csv(get_ready_information())
  138. logger.info("Stop programm")