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