main.py 4.1 KB

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