main.py 4.8 KB

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