удаление конфига, работа над бэкапами, работа над реконфигурацией
This commit is contained in:
		
							
								
								
									
										91
									
								
								hlna.py
									
									
									
									
									
								
							
							
						
						
									
										91
									
								
								hlna.py
									
									
									
									
									
								
							| @@ -5,6 +5,7 @@ import sys | |||||||
| import zlib | import zlib | ||||||
| import time | import time | ||||||
| import struct | import struct | ||||||
|  | import tarfile | ||||||
| import logging | import logging | ||||||
| import datetime | import datetime | ||||||
| import requests | import requests | ||||||
| @@ -12,7 +13,6 @@ import subprocess | |||||||
|  |  | ||||||
| import yaml | import yaml | ||||||
| import click | import click | ||||||
| import zipfile |  | ||||||
| import colorama | import colorama | ||||||
|  |  | ||||||
| from pathlib import Path | from pathlib import Path | ||||||
| @@ -67,41 +67,44 @@ def hlna(): | |||||||
|  |  | ||||||
| @hlna.command(help='Восстановление бэкапов серверов в <hlna restore ark>') | @hlna.command(help='Восстановление бэкапов серверов в <hlna restore ark>') | ||||||
| @click.argument('g', nargs=1) | @click.argument('g', nargs=1) | ||||||
|  | @click.option('-m', default='all', help="Название карты для запуска или all для запуска всех карт") | ||||||
| @click.option('-d', required=True, help="Путь до zip архива") | @click.option('-d', required=True, help="Путь до zip архива") | ||||||
| def restore(g, d): | def restore(g, m, d): | ||||||
|     """Получение пути к файлам внутри архива""" |     """Получение пути к файлам внутри архива""" | ||||||
|     with zipfile.ZipFile(d, 'r') as zip_file: |     with tarfile.open(d, 'r') as tar_file: | ||||||
|         files = zip_file.namelist() |         files = tar_file.namelist() | ||||||
|         """Извлечение файлов""" |         """Извлечение файлов""" | ||||||
|     for i in files: |     for i in files: | ||||||
|         with zipfile.ZipFile(d, 'r') as zip_file: |         with tar_file.extract(d, 'r:gz') as tar_file: | ||||||
|             path_extarct = "./" if g == 'test' else "/" |             path_extarct = "./" if g == 'test' else "/" | ||||||
|             zip_file.extract(i, path_extarct) |             tar_file.extract(i, path_extarct) | ||||||
|             print(i, colorama.Fore.GREEN + "- перемещен" + colorama.Style.RESET_ALL) |             print(i, colorama.Fore.GREEN + "- перемещен" + colorama.Style.RESET_ALL) | ||||||
|     print_line(f"Бэкап {d} восстановлен", flag="GREEN") |     print_line(f"Бэкап {d} восстановлен", flag="GREEN") | ||||||
|  |  | ||||||
|  |  | ||||||
| @hlna.command(help='Бэкап серверов выбранной игры <hlna backup ark') | @hlna.command(help='Бэкап серверов выбранной игры <hlna backup ark') | ||||||
| @click.argument('g', nargs=1) | @click.argument('g', nargs=1) | ||||||
| def backup(g): | @click.option('-m', default='all', help="Название карты для запуска или all для запуска всех карт") | ||||||
|  | def backup(g, m): | ||||||
|     if g == "ark" or g == "ark_test": |     if g == "ark" or g == "ark_test": | ||||||
|         source = [f"{dir_config}"] |         name_server = choose_map(g, m) | ||||||
|         #  backup_path = input("Введите конечный путь для бэкапа, по умолчанию ******") |  | ||||||
|         backup_path = f"{dir_server_ark}Backups" if g == "ark" else f"{dir_server_ark}Backups/test_backup" |         backup_path = f"{dir_server_ark}Backups" if g == "ark" else f"{dir_server_ark}Backups/test_backup" | ||||||
|         if not backup_path: |         if not backup_path: | ||||||
|             backup_path = f"{dir_server_ark}Backups" |             backup_path = f"{dir_server_ark}Backups" | ||||||
|          |         for i in name_server: | ||||||
|         target = f"{backup_path}/" + g + "_backup-" + time.strftime('%Y_%m_%d') + '.zip' |             source = [f"{dir_maps_ark}"] | ||||||
|         create_dir(backup_path) |             target = f"{backup_path}/{g}_{i}_backup_{time.strftime('%Y_%m_%d')}.tar" | ||||||
|         with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED, True) as myzip: |             create_dir(backup_path) | ||||||
|             for source_folder in source: |             with tarfile.open(target, 'w') as mytar: | ||||||
|                 for root, dirs, files in os.walk(source_folder): |                 for source_folder in source: | ||||||
|                     for file in files: |                     for root, dirs, files in os.walk(source_folder): | ||||||
|                         path = os.path.join(root, file) |                         for file in files: | ||||||
|                         myzip.write(path) |                             name, ext = os.path.splitext(file) | ||||||
|                         print(path, colorama.Fore.GREEN + "- перемещен" + colorama.Style.RESET_ALL) |                             if ext == i: | ||||||
|                          |                                 path = os.path.join(root, name) | ||||||
|         print(colorama.Fore.GREEN + f"Конфиги сохранены в {target}" + colorama.Style.RESET_ALL) |                                 mytar.add(path) | ||||||
|  |                                 print(path, colorama.Fore.GREEN + "- перемещен" + colorama.Style.RESET_ALL) | ||||||
|  |             print_line(f"Конфиги сохранены в {target}", flag="GREEN") | ||||||
|     elif g == "7days": |     elif g == "7days": | ||||||
|         pass |         pass | ||||||
|     else: |     else: | ||||||
| @@ -572,6 +575,15 @@ WantedBy=default.target | |||||||
|     os.system(f"systemctl --user enable {unit_name}") |     os.system(f"systemctl --user enable {unit_name}") | ||||||
|  |  | ||||||
|  |  | ||||||
|  | @hlna.command(help='Удаление конфигурации сервера') | ||||||
|  | @click.argument('g', nargs=1) | ||||||
|  | @click.option('-m', default='all', help="Название карты для запуска или all для запуска всех карт") | ||||||
|  | def remove(g, m): | ||||||
|  |     if g == "ark": | ||||||
|  |         name_server = choose_map(g, m) | ||||||
|  |         os.remove(f"{dir_maps_ark}{name_server}") | ||||||
|  |  | ||||||
|  |  | ||||||
| @hlna.command(help='Скачивание и установка модов <hlna ark -m all -i 111111111>') | @hlna.command(help='Скачивание и установка модов <hlna ark -m all -i 111111111>') | ||||||
| @click.argument('g', nargs=1) | @click.argument('g', nargs=1) | ||||||
| @click.option('-m', default='all', help="Название карты для запуска или all для запуска всех карт") | @click.option('-m', default='all', help="Название карты для запуска или all для запуска всех карт") | ||||||
| @@ -740,20 +752,25 @@ def moddownload(g, m, id_mod, dir_mod_ark): | |||||||
| def switch(g, m, e): #добавить all | def switch(g, m, e): #добавить all | ||||||
|     g = g.lower() |     g = g.lower() | ||||||
|     if g == "ark": |     if g == "ark": | ||||||
|  |         print_line("Вход в ark", flag="RED") | ||||||
|         m = m.split(",") |         m = m.split(",") | ||||||
|         if not os.path.isdir(dir_deactivated): |         if not os.path.isdir(dir_deactivated): | ||||||
|             create_dir(dir_deactivated) |             create_dir(dir_deactivated) | ||||||
|         if e: |         if e: | ||||||
|             port_s, query_p, rcon_p = ports_array() |             port_s, query_p, rcon_p = ports_array() | ||||||
|  |  | ||||||
|         state_config = list_config if e else delist_config |         state_config = delist_config if e else list_config | ||||||
|         state_msg = "активных" if e else "не активных" |         state_msg = "активных" if e else "не активных" | ||||||
|         for i in m: |         for i in m: | ||||||
|             try: |             try: | ||||||
|                 if i in state_config: |                 print_line("Вход в try", flag="RED") | ||||||
|  |                 state_config1 = list_config if e else delist_config | ||||||
|  |                 if i in state_config1: | ||||||
|  |                     print_line("Вход в определение статуса", flag="RED") | ||||||
|                     print_line(f"Карта {i} уже есть в {state_msg}", flag="CYAN") |                     print_line(f"Карта {i} уже есть в {state_msg}", flag="CYAN") | ||||||
|                     continue |                     continue | ||||||
|                 data = read_yaml(i, not e) |                 data = read_yaml(i, not e, g="ark") | ||||||
|  |                 print_line(f"дата {data}", flag="RED") | ||||||
|                 if e: |                 if e: | ||||||
|                     data['Port'] = ports(data['Port'], port_s, e) |                     data['Port'] = ports(data['Port'], port_s, e) | ||||||
|                     data['QueryPort'] = ports(data['QueryPort'], port_s, e) |                     data['QueryPort'] = ports(data['QueryPort'], port_s, e) | ||||||
| @@ -767,14 +784,15 @@ def switch(g, m, e): #добавить all | |||||||
|                     with open(f"{dir_logs}{date}.log", "a") as f: |                     with open(f"{dir_logs}{date}.log", "a") as f: | ||||||
|                         f.write(f"[{t}] Сервер {i} перемещён из {state_msg}\n")# переписать эту залупу |                         f.write(f"[{t}] Сервер {i} перемещён из {state_msg}\n")# переписать эту залупу | ||||||
|                 else: |                 else: | ||||||
|  |                     print_line("Вход в отключение", flag="RED") | ||||||
|                     x = os.system(f"mv {dir_maps_ark}{i} {dir_deactivated} >> {dir_logs}{date} 2>&1") |                     x = os.system(f"mv {dir_maps_ark}{i} {dir_deactivated} >> {dir_logs}{date} 2>&1") | ||||||
|                     with open(f"{dir_logs}{date}.log", "a") as f: |                     with open(f"{dir_logs}{date}.log", "a") as f: | ||||||
|                         f.write(f"[{t}] Сервер {i} перемещён из {state_msg}\n") |                         f.write(f"[{t}] Сервер {i} перемещён из {state_msg}\n") | ||||||
|                 if x == 0: |                 if x == 0: | ||||||
|                     print_line(f"Готов - {i}", flag="GREEN") |  | ||||||
|                     #start = "start" if e else "stop" |                     #start = "start" if e else "stop" | ||||||
|                     enable = "enable" if e else "disable" |                     enable = "enable" if e else "disable" | ||||||
|                     os.system(f"systemctl --user {enable} ark_{i}") |                     os.system(f"systemctl --user {enable} ark_{i.lower()}") | ||||||
|  |                     print_line(f"Выполнено для сервера- {i}", flag="GREEN") | ||||||
|                 else: |                 else: | ||||||
|                     print_line(f"Ошибка перемещения {i}", flag="RED") |                     print_line(f"Ошибка перемещения {i}", flag="RED") | ||||||
|             except: |             except: | ||||||
| @@ -899,8 +917,10 @@ def start_stop(action, g, m): | |||||||
|  |  | ||||||
| def read_yaml(list_config=list_config, flag=True, m="", g=""): | def read_yaml(list_config=list_config, flag=True, m="", g=""): | ||||||
|     """Читает конфиги активных или неактивных карт в зависимости от флага и отдаёт данные туда где их запросили""" |     """Читает конфиги активных или неактивных карт в зависимости от флага и отдаёт данные туда где их запросили""" | ||||||
|  |     print_line("Вход в read_yaml", flag="RED") | ||||||
|     g = g.lower() |     g = g.lower() | ||||||
|     if g == "ark": |     if g == "ark": | ||||||
|  |         print_line("Вход в арк в чтении", flag="RED") | ||||||
|         if m == "all": |         if m == "all": | ||||||
|             list_config=list_config |             list_config=list_config | ||||||
|         path_yaml = f"{dir_maps_ark}{list_config}" if flag else f"{dir_deactivated}{list_config}" |         path_yaml = f"{dir_maps_ark}{list_config}" if flag else f"{dir_deactivated}{list_config}" | ||||||
| @@ -908,6 +928,7 @@ def read_yaml(list_config=list_config, flag=True, m="", g=""): | |||||||
|         path_yaml = dir_config + "config" |         path_yaml = dir_config + "config" | ||||||
|     with open(path_yaml, "r") as yamlfile: |     with open(path_yaml, "r") as yamlfile: | ||||||
|         data = yaml.load(yamlfile, Loader=yaml.FullLoader) |         data = yaml.load(yamlfile, Loader=yaml.FullLoader) | ||||||
|  |         print_line("Выход из read_yaml", flag="RED") | ||||||
|     return data[0]  # возвращаем словарь со всеми значениями |     return data[0]  # возвращаем словарь со всеми значениями | ||||||
|  |  | ||||||
|  |  | ||||||
| @@ -936,14 +957,16 @@ def choose_map(g, m, list_config=list_config): | |||||||
|                     print_line('Найдены сервера с этой картой', flag="CYAN") |                     print_line('Найдены сервера с этой картой', flag="CYAN") | ||||||
|                     for i, map in enumerate(name_servers): |                     for i, map in enumerate(name_servers): | ||||||
|                         print_line(f"{i + 1}) {map}", flag="CYAN") |                         print_line(f"{i + 1}) {map}", flag="CYAN") | ||||||
|                     while True: |                     if i != 0: | ||||||
|                         try: |                         while True: | ||||||
|                             x = input("Выберите сервер из списка, либо несколько через запятую: ").split(',') |                             try: | ||||||
|                             x = [int(i) for i in x] |                                 x = input("Выберите сервер из списка, либо несколько через запятую: ").split(',') | ||||||
|                             break |                                 x = [int(i) for i in x] | ||||||
|                         except: |                                 break | ||||||
|                             print_line("Неправильный ввод", flag="RED") |                             except: | ||||||
|                     print(name_servers) |                                 print_line("Неправильный ввод", flag="RED") | ||||||
|  |                     else: | ||||||
|  |                         x = [1] | ||||||
|                     for i in x: |                     for i in x: | ||||||
|                         new_arr.append(name_servers[i - 1]) |                         new_arr.append(name_servers[i - 1]) | ||||||
|                     print_line(f"Выбранные сервера: {name_servers}", flag="CYAN") |                     print_line(f"Выбранные сервера: {name_servers}", flag="CYAN") | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user