main.py 5.0 KB

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