123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- import csv, os, re, sys, argparse
- from logger import *
- from datetime import datetime
- import pandas as pd
-
- parse = argparse.ArgumentParser(
- description="Программа для сбора информации из csv файлов")
- parse.add_argument('-p', '--path', help='Указать в какой директории искать',
- default=os.path.dirname(sys.argv[0]))
- parse.add_argument('-e', '--open_encoding',
- help='Указать в какой кодировке открывать', default='utf-16')
- args = parse.parse_args()
- print(args)
- LIST_BAD_ADAPTER = ['Wireless', 'Bluetooth', 'Wireless', 'WiFi',
- 'Kaspersky', 'VirtualBox', 'TAP-Windows',
- 'Wintun', '802.11', 'VMware', 'VPN', 'Wi-Fi',
- '1394', 'Mobile']
- # Количетсво интерфейсов по умолчанию
- COUNT_INTERFACE = 1
- def check_correct_controller(name) -> bool:
- return any(ext not in name for ext in LIST_BAD_ADAPTER)
- class ObjectReady:
- def get_len_dict(self) -> int:
- return len(self.__dict__)
- def get_row(self) -> str:
- return self.__dict__
- def get_paths() -> list:
- list_path = []
- for root, _, files in os.walk(args.path):
- list_path += [
- F"{root}/{file}" for file in files if file.split('.')[-1] == 'csv' and "result" not in file]
- return list_path
- def convert_mb_to_gb(val: str) -> str:
- numbers = int(''.join([x for x in val if x.isdigit()]))
- return str(round(numbers/1024, 1))+' GB'
- def get_ser_motherboard(row: list) -> str:
- try:
- return row if row not in ['To be filled by O.E.M.', 'Default string'] else None
- except IndexError:
- pass
- def get_data_from_file(path: str, obj: ObjectReady) -> None:
- global COUNT_INTERFACE
-
- with open(path, 'r', encoding=args.open_encoding) as file:
-
- cs = csv.reader(file, delimiter=',')
- next(cs)
- line_info_computers = next(cs)
- obj.os = line_info_computers[7]
- obj.cpu = line_info_computers[13]
- obj.ram = convert_mb_to_gb(line_info_computers[14])
- obj.motherboard = None
- obj.count_interface = 0
- count_interface = 0
-
- for line in cs:
- data = list(pd.Series(line))
- if data[0] == '6200':
- obj.motherboard = get_ser_motherboard(data[6])
- if data[0] == '2600' and len(data) > 2 and check_correct_controller(data[3]):
- setattr(obj, F'ip{count_interface+1}', data[6].split(' ')[0])
- setattr(obj, F'mac{count_interface+1}', data[-3])
- count_interface += 1
- # Увеличиваем значение если количестов интерфейсов больше в этой строке
- obj.count_interface = count_interface
- if count_interface > COUNT_INTERFACE:
- COUNT_INTERFACE = count_interface
- file.close()
- def get_ready_information() -> list[ObjectReady]:
- list_objects = []
- for path in get_paths():
-
- obj = ObjectReady()
- obj.frame = os.path.basename(os.path.dirname(path))
- obj.cabinet = re.findall(
- r"\/([\w+?\ ?[а-яА-Я]+\ ?|\w+?\ ?[a-zA-Z]+\ ?|\d+])[\.|\,]", path)[-1]
- try:
- get_data_from_file(path, obj)
- except UnicodeDecodeError as ude:
- logger.error(F"{path} --> {ude}\n")
- except UnicodeError as er:
- logger.error(F"{path} --> {er}\n")
- except StopIteration as si:
- logger.error(F"{path} --> Пустой файл или тмпо того\n")
- list_objects.append(obj)
- return list_objects
- def create_csv(list_obj: list[ObjectReady]) -> None:
- namefile = F"result-{datetime.today().strftime('%Y-%m-%d-%H.%M.%S')}.xlsx"
- data = [row.get_row() for row in list_obj]
- df = pd.DataFrame(data=data)
- df.to_excel(namefile, index= False)
-
- if __name__ == '__main__':
- create_logger()
-
- logger.info("Start programm")
- logger.info(F"Base dir: {args.path}")
-
- create_csv(get_ready_information())
- logger.info("Stop programm")
|