main.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. import csv
  2. import os
  3. import sys
  4. import argparse
  5. from logger import *
  6. from datetime import datetime
  7. import pandas as pd
  8. from tqdm import tqdm
  9. ARGS = None
  10. parse = argparse.ArgumentParser(
  11. description="Программа для сбора информации из csv файлов")
  12. parse.add_argument('-p', '--path', help='Указать в какой директории искать',
  13. default=os.path.dirname(sys.argv[0]))
  14. parse.add_argument('-e', '--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. def __init__(self) -> None:
  27. self.frame: str = None
  28. self.cabinet: str = None
  29. self.os: str = None
  30. self.cpu: str = None
  31. self.ram: str = None
  32. self.motherboard: str = None
  33. self.count_interface: int = 0
  34. def get_len_dict(self) -> int:
  35. return len(self.__dict__)
  36. def get_row(self) -> str:
  37. return self.__dict__
  38. def get_paths() -> list:
  39. list_path = []
  40. for root, _, files in os.walk(ARGS.path):
  41. list_path += [
  42. F"{root}/{file}" for file in files if file.split('.')[-1] == 'csv' and "result" not in file]
  43. return list_path
  44. def convert_mb_to_gb(val: str) -> str:
  45. numbers = int(''.join([x for x in val if x.isdigit()]))
  46. return str(round(numbers/1024, 1))+' GB'
  47. def get_ser_motherboard(row: list) -> str:
  48. try:
  49. return row if row not in ['To be filled by O.E.M.', 'Default string'] else None
  50. except IndexError:
  51. pass
  52. def get_data_from_file(path: str, obj: ObjectReady) -> None:
  53. global COUNT_INTERFACE
  54. with open(path, 'r', encoding=ARGS.open_encoding) as file:
  55. cs = csv.reader(file, delimiter=',')
  56. count_interface = 0
  57. for line in cs:
  58. data = list(pd.Series(line))
  59. match data[0]:
  60. case '300':
  61. obj.os = data[7]
  62. obj.cpu = data[13]
  63. obj.ram = convert_mb_to_gb(data[14])
  64. case '6200':
  65. obj.motherboard = get_ser_motherboard(data[6])
  66. case '2600':
  67. if len(data) > 2 and check_correct_controller(data[3]):
  68. setattr(obj, F'ip{count_interface+1}',
  69. data[6].split(' ')[0])
  70. setattr(obj, F'mac{count_interface+1}', data[-3])
  71. count_interface += 1
  72. case _: continue
  73. # Увеличиваем значение если количестов интерфейсов больше в этой строке
  74. obj.count_interface = count_interface
  75. if count_interface > COUNT_INTERFACE:
  76. COUNT_INTERFACE = count_interface
  77. def get_ready_information() -> list[ObjectReady]:
  78. list_objects = []
  79. paths = get_paths()
  80. progressbar = tqdm(range(0, len(paths)), desc='Progress')
  81. for path in paths:
  82. obj = ObjectReady()
  83. obj.frame = os.path.basename(os.path.dirname(path))
  84. try:
  85. obj.cabinet = str(os.path.basename(path)).split('.')[0]
  86. except IndexError as er:
  87. logger.error(F"index error path: {path}")
  88. continue
  89. try:
  90. get_data_from_file(path, obj)
  91. logger.info(F'Parse success file: {path}')
  92. except UnicodeDecodeError as ude:
  93. logger.error(F"{path} --> {ude}")
  94. except UnicodeError as er:
  95. logger.error(F"{path} --> {er}")
  96. except StopIteration:
  97. logger.error(F"{path} --> Пустой файл или тмпо того")
  98. list_objects.append(obj)
  99. progressbar.update(1)
  100. return list_objects
  101. def create_header_interface() -> str:
  102. return ARGS.delimiter.join([
  103. ARGS.delimiter.join((F"ip{i+1}", F"mac{i+1}"))
  104. for i in range(COUNT_INTERFACE)
  105. ])
  106. def create_csv(list_obj: list[ObjectReady]) -> None:
  107. namefile = F"result-{datetime.today().strftime('%Y-%m-%d-%H.%M.%S')}.xlsx"
  108. data = [row.get_row() for row in list_obj]
  109. df = pd.DataFrame(data=data)
  110. df.to_excel(namefile, index=False)
  111. if __name__ == '__main__':
  112. try:
  113. logger.info("Start programm")
  114. try:
  115. ARGS = parse.parse_args(sys.argv[1:])
  116. except argparse.ArgumentError:
  117. parse.print_help()
  118. create_logger()
  119. logger.info(F"Base dir: {ARGS.path}")
  120. create_csv(get_ready_information())
  121. logger.info("Stop programm")
  122. except KeyboardInterrupt:
  123. logger.info("Отмена операции")