main.py 4.8 KB

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