811 lines
33 KiB
Python
Executable File
811 lines
33 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
import os
|
||
import re
|
||
import sys
|
||
import zlib
|
||
import struct
|
||
import logging
|
||
import datetime
|
||
import subprocess
|
||
|
||
import yaml
|
||
import click
|
||
import colorama
|
||
|
||
from pathlib import Path
|
||
from rcon.source import Client
|
||
|
||
home_dir = Path.home()
|
||
|
||
logging.basicConfig(stream=sys.stderr, level=logging.CRITICAL)
|
||
|
||
|
||
def find_file(path):
|
||
"""Находим все конфиги в зависимости от пути"""
|
||
arr = next(os.walk(path), (None, None, []))[2] # [] if no file
|
||
if '.directory' in arr:
|
||
arr.remove('.directory')
|
||
return arr
|
||
|
||
|
||
dir_config = f"{home_dir}/.config/hlna/"
|
||
dir_maps_ark = f"{dir_config}ARK/"
|
||
dir_deactivated = f"{dir_maps_ark}deactivated/"
|
||
list_config = find_file(dir_maps_ark)
|
||
delist_config = find_file(dir_deactivated)
|
||
|
||
|
||
def create_dir(directory):
|
||
"""Проверка и создание директории"""
|
||
if not os.path.exists(directory):
|
||
os.makedirs(directory)
|
||
|
||
|
||
create_dir(dir_config)
|
||
|
||
|
||
def path_server():
|
||
"""Получение пути для хранения файлов серверов, записываем путь в yaml файл"""
|
||
dir_server = input(f"""Укажите путь до каталога, где будут храниться файлы сервера. По-умолчанию {home_dir}/Servers/
|
||
:""")
|
||
if not dir_server:
|
||
dir_server = f"{home_dir}/Servers/"
|
||
yaml_create("path_server", dir_server)
|
||
return dir_server
|
||
|
||
|
||
@click.group()
|
||
def hlna():
|
||
pass
|
||
|
||
|
||
def unpack(src, dst):
|
||
"""Добавить документацию"""
|
||
with open(src, 'rb') as f:
|
||
sigver = struct.unpack('q', f.read(8))[0]
|
||
unpacked_chunk = f.read(8)
|
||
packed = f.read(8)
|
||
unpacked = f.read(8)
|
||
size_unpacked_chunk = struct.unpack('q', unpacked_chunk)[0]
|
||
size_packed = struct.unpack('q', packed)[0]
|
||
size_unpacked = struct.unpack('q', unpacked)[0]
|
||
|
||
# Verify the integrity of the Archive Header
|
||
if sigver == 2653586369:
|
||
if isinstance(size_unpacked_chunk, int) and isinstance(size_packed, int) and isinstance(size_unpacked, int):
|
||
logging.info("Archive is valid.")
|
||
logging.debug(
|
||
f"Archive header size information. Unpacked Chunk: {size_unpacked_chunk}({unpacked_chunk}) Full Packed: {size_packed}({packed}) Full Unpacked: {size_unpacked}({unpacked})")
|
||
|
||
# Obtain the Archive Compression Index
|
||
compression_index = []
|
||
size_indexed = 0
|
||
while size_indexed < size_unpacked:
|
||
raw_compressed = f.read(8)
|
||
raw_uncompressed = f.read(8)
|
||
compressed = struct.unpack('q', raw_compressed)[0]
|
||
uncompressed = struct.unpack('q', raw_uncompressed)[0]
|
||
compression_index.append((compressed, uncompressed))
|
||
size_indexed += uncompressed
|
||
logging.debug(
|
||
f"{len(compression_index)}: {size_indexed}/{size_unpacked} ({compressed}/{uncompressed}) - {raw_compressed} - {raw_uncompressed}")
|
||
|
||
if size_unpacked != size_indexed:
|
||
msg = f"Header-Index mismatch. Header indicates it should only have {size_unpacked} bytes when uncompressed but the index indicates {size_indexed} bytes."
|
||
logging.critical(msg)
|
||
return print(msg)
|
||
|
||
|
||
# Read the actual archive data
|
||
data = b''
|
||
read_data = 0
|
||
for compressed, uncompressed in compression_index:
|
||
compressed_data = f.read(compressed)
|
||
uncompressed_data = zlib.decompress(compressed_data)
|
||
|
||
# Verify the size of the data is consistent with the archives index
|
||
if len(uncompressed_data) == uncompressed:
|
||
data += uncompressed_data
|
||
read_data += 1
|
||
|
||
# Verify there is only one partial chunk
|
||
if len(uncompressed_data) != size_unpacked_chunk and read_data != len(compression_index):
|
||
msg = f"Index contains more than one partial chunk: was {len(uncompressed_data)} when the full chunk size is {size_unpacked_chunk}, chunk {read_data}/{len(compression_index)}"
|
||
logging.critical(msg)
|
||
return print(msg)
|
||
else:
|
||
msg = f"Uncompressed chunk size is not the same as in the index: was {len(uncompressed_data)} but should be {uncompressed}."
|
||
logging.critical(msg)
|
||
return print(msg)
|
||
else:
|
||
msg = f"Data types in the headers should be int's. Size Types: unpacked_chunk({type(size_unpacked_chunk)}), packed({type(size_packed)}), unpacked({type(size_unpacked)})"
|
||
logging.critical(msg)
|
||
return print(msg)
|
||
else:
|
||
msg = "The signature and format version is incorrect. Signature was {} should be 2653586369.".format(sigver)
|
||
logging.critical(msg)
|
||
return print(msg)
|
||
|
||
# Write the extracted data to disk
|
||
with open(dst, 'wb') as f:
|
||
f.write(data)
|
||
logging.info("Archive has been extracted.")
|
||
|
||
|
||
|
||
|
||
|
||
def print_line(*text):
|
||
"""Добавление тире вокруг текста, покраска"""
|
||
print(colorama.Fore.YELLOW + "-" * 30)
|
||
print(colorama.Fore.GREEN, *text)
|
||
print(colorama.Fore.YELLOW + "-" * 30 + colorama.Style.RESET_ALL)
|
||
|
||
|
||
def check_int(number=""):
|
||
"""Проверка на ввод числа"""
|
||
while True:
|
||
try:
|
||
x = input(number)
|
||
if x == "":
|
||
return 0
|
||
x = int(x)
|
||
return x
|
||
except ValueError:
|
||
print_line("Введите число")
|
||
|
||
|
||
@hlna.command(help='Выбор игры и сбор настроек для сервера(-ов)')
|
||
def config():
|
||
count_game = check_int("""Выберите игру для конфигурирования
|
||
1. ARK Survival Evolved
|
||
2. 7 Days to Die
|
||
: """)
|
||
if count_game == 1:
|
||
config_ark()
|
||
elif count_game == 2:
|
||
config_7daystodie()
|
||
else:
|
||
print_line("Пока есть только ARK и 7Days xD")
|
||
|
||
|
||
def config_ark(list_config=list_config):
|
||
"""конфигурирование сервера арк"""
|
||
create_dir(dir_server_ark)
|
||
create_dir(dir_maps_ark)
|
||
path_server()
|
||
"""Сбор данных для конфига"""
|
||
port_s = []
|
||
rcon_p = []
|
||
query_p = []
|
||
|
||
cluster_id = ""
|
||
cluster_dir_override = ""
|
||
|
||
count_cluster = check_int("""Укажите требуется ли кластер? default: Нет
|
||
1. Да
|
||
2. Нет
|
||
: """)
|
||
if count_cluster == 1:
|
||
cluster_server = True
|
||
while True:
|
||
cluster_id = input("Укажите id для кластера, любое сочетание символов: \n")
|
||
if cluster_id == '':
|
||
print("Введите символы: ")
|
||
else:
|
||
create_dir(dir_server_ark + cluster_id)
|
||
cluster_dir_override = (dir_server_ark + cluster_id)
|
||
break
|
||
else:
|
||
cluster_server = False
|
||
|
||
if list_config:
|
||
print("Уже установленные карты: ")
|
||
for i in list_config:
|
||
data = read_yaml(i, game="ARK")
|
||
print(f"{i} : {data['map']}")
|
||
|
||
count_maps = check_int("Укажите количество карт: \n")
|
||
if count_maps == 0: # 0 возвращает check_int когда, ничего не было введено
|
||
count_maps = 1
|
||
|
||
for i in range(count_maps):
|
||
while True:
|
||
"""Проверка на выбор карты из списка"""
|
||
amount_map = check_int("""Выберите карту из списка указав номер
|
||
1. The Island
|
||
2. The Center
|
||
3. Scorched Earth
|
||
4. Ragnarok
|
||
5. Aberration
|
||
6. Extinction
|
||
7. Valguero
|
||
8. Genesis: Part 1
|
||
9. Crystal Isles
|
||
10. Genesis: Part 2
|
||
11. Lost Island
|
||
12. Fjordur
|
||
: """)
|
||
if amount_map == 0: # 0 возвращает check_int когда, ничего не было введено
|
||
amount_map = i + 1
|
||
if 0 < amount_map <= 12:
|
||
break
|
||
|
||
if list_config:
|
||
for k in list_config:
|
||
data_port = read_yaml(k, game="ARK")
|
||
port_s.append(data_port['Port'])
|
||
rcon_p.append(data_port['RCONPort'])
|
||
query_p.append(data_port['QueryPort'])
|
||
|
||
if amount_map == 1:
|
||
map_s = "TheIsland"
|
||
elif amount_map == 2:
|
||
map_s = "TheCenter"
|
||
elif amount_map == 3:
|
||
map_s = "ScorchedEarth_P"
|
||
elif amount_map == 4:
|
||
map_s = "Ragnarok"
|
||
elif amount_map == 5:
|
||
map_s = "Aberration_P"
|
||
elif amount_map == 6:
|
||
map_s = "Extinction"
|
||
elif amount_map == 7:
|
||
map_s = "Valguero_P"
|
||
elif amount_map == 8:
|
||
map_s = "Genesis"
|
||
elif amount_map == 9:
|
||
map_s = "CrystalIsles"
|
||
elif amount_map == 10:
|
||
map_s = "Gen2"
|
||
elif amount_map == 11:
|
||
map_s = "LostIsland"
|
||
elif amount_map == 12:
|
||
map_s = "Fjordur"
|
||
else:
|
||
# Если вдруг каким-то боком проверка не отработает и не будет нужной цифры
|
||
map_s = 'TheIsland'
|
||
|
||
def ports(ports_arr):
|
||
while True:
|
||
port = check_int("")
|
||
if not port:
|
||
if not ports_arr:
|
||
return 0
|
||
else:
|
||
port = max(ports_arr) + 2
|
||
if port in ports_arr:
|
||
print("Порт уже занят")
|
||
else:
|
||
return port
|
||
|
||
if list_config:
|
||
data = read_yaml(list_config[-1], game="ARK")
|
||
while True:
|
||
name_server = input("Укажите название Сервера: \n")
|
||
if name_server == "":
|
||
if map_s in list_config:
|
||
count = 1
|
||
new_name = map_s
|
||
while new_name in list_config:
|
||
new_name = f"{map_s}{str(count)}"
|
||
count += 1
|
||
list_config.append(new_name)
|
||
print(list_config)
|
||
break
|
||
else:
|
||
list_config.append(map_s)
|
||
break
|
||
else:
|
||
if name_server in list_config:
|
||
print_line("Имя занято")
|
||
else:
|
||
list_config.append(name_server) # если enter, то ставим последним элементом карту
|
||
break
|
||
|
||
print("Укажите порт сервера: ")
|
||
port_server = ports(port_s)
|
||
if port_server == 0:
|
||
port_server = 7777
|
||
print("Порт Сервера=", port_server)
|
||
print("Укажите query порт сервера: ")
|
||
query_port = ports(query_p)
|
||
if query_port == 0:
|
||
query_port = 27015
|
||
print("Query Port=", query_port)
|
||
|
||
rcon_enabled = True
|
||
if rcon_p == []:
|
||
rcon_port = 27020
|
||
else:
|
||
rcon_port = max(rcon_p) + 1
|
||
|
||
password_server = input("Укажите пароль Сервера: \n")
|
||
adminpassword_server = 123
|
||
max_players = check_int("Укажите максимальное количество игроков: \n")
|
||
if max_players == 0:
|
||
max_players = 70
|
||
|
||
print("Передавать сервер в глобальный список серверов steam?")
|
||
listen_server_amount = check_int("""\n
|
||
1. Да
|
||
2. Нет
|
||
:""")
|
||
if listen_server_amount == 1:
|
||
listen_server = True
|
||
elif listen_server_amount == 2:
|
||
listen_server = False
|
||
else:
|
||
listen_server = True
|
||
"""Вызов создания конфига"""
|
||
yaml_create("ARK", "", cluster_server, map_s, list_config[-1], port_server, query_port,
|
||
rcon_enabled, rcon_port, adminpassword_server, password_server, max_players,
|
||
cluster_id, cluster_dir_override, listen_server)
|
||
|
||
|
||
def config_7daystodie():
|
||
"""конфигурирование сервера 7 days to die"""
|
||
list_simvols = ("$","@","-",".","%","{","}","+","/")
|
||
create_dir(dir_server_7days)
|
||
config_7days = input("Введите имя конфига (serverconfig):\n")
|
||
if config_7days == "":
|
||
config_7days = "serverconfig"
|
||
elif config_7days == "serverconfig":
|
||
config_7days = "serverconfig"
|
||
elif config_7days in list_simvols:
|
||
print_line("Запрещённые символы")
|
||
else:
|
||
xml_parser()
|
||
systemd_unit_create("7Days", config_7days)
|
||
|
||
|
||
def xml_parser():
|
||
"""добавить документацию"""
|
||
print("Я пока не умею парсить xml))")
|
||
|
||
|
||
def yaml_create(game, dir_server="", cluster_server="", map_s="", name_server="", port_server="", query_port="",
|
||
rcon_enabled="", rcon_port="", adminpassword_server="", password_server="", max_players="",
|
||
id_mods_ark="", cluster_id="", cluster_dir_override="", listen_server=""):
|
||
"""Создаёт на основании собранных данных yaml конфиг"""
|
||
if game == "ARK":
|
||
path_yaml = dir_maps_ark + name_server
|
||
settings = [
|
||
{
|
||
'map': map_s,
|
||
'Cluster': cluster_server,
|
||
'SessionName': name_server,
|
||
'Port': port_server,
|
||
'QueryPort': query_port,
|
||
'RCONEnabled': rcon_enabled,
|
||
'RCONPort': rcon_port,
|
||
'ServerAdminPassword': adminpassword_server,
|
||
'ServerPassword': password_server,
|
||
'MaxPlayers': max_players,
|
||
'ModsId': id_mods_ark,
|
||
'Listen': listen_server,
|
||
'ServerPath': dir_server_ark,
|
||
'clusterid': cluster_id,
|
||
'clusterdir': cluster_dir_override
|
||
}
|
||
]
|
||
elif game == "path_server":
|
||
path_yaml = dir_config + "config"
|
||
settings = [
|
||
{
|
||
'path_server': dir_server
|
||
}
|
||
]
|
||
|
||
with open(path_yaml, 'w') as yamlfile:
|
||
yaml.dump(settings, yamlfile)
|
||
print(colorama.Fore.GREEN + "Конфиг создан" + colorama.Style.RESET_ALL)
|
||
if game != "path_server":
|
||
systemd_unit_create(game)
|
||
|
||
|
||
def systemd_unit_create(game, config_7days="", name_server=list_config):
|
||
"""Создаёт на основании yaml конфига systemd юнит"""
|
||
if game == "ARK":
|
||
id_game = "376030"
|
||
for i in name_server:
|
||
data = read_yaml(i, game="ARK")
|
||
ntff = "" if not data['Cluster'] else "-NoTransferFromFiltering"
|
||
unit_dir_server = dir_server_ark
|
||
systemd_unit_exec = f"{dir_server_exec}ShooterGameServer {data['map']}?listen={data['Listen']}?GameModIds=2112724006?SessionName={data['SessionName']}?Port={data['Port']}?QueryPort={data['QueryPort']}?RCONEnabled={data['RCONEnabled']}?RCONPort={data['RCONPort']}?ServerAdminPassword={data['ServerAdminPassword']}??MaxPlayers={data['MaxPlayers']} -clusterid={data['clusterid']} -ClusterDirOverride={data['clusterdir']} {ntff}"
|
||
unit_file = f"{dir_unit}ark_{data['SessionName']}.service".lower()
|
||
elif game == "7Days":
|
||
id_game = "294420"
|
||
# сюда дописать обращение к xml_parser для получения уникального имени сервера
|
||
unit_dir_server = dir_server_7days
|
||
systemd_unit_exec = f"{dir_server_7days}startserver.sh -configfile={config_7days}.xml"
|
||
unit_file = f"{dir_unit}7days.service".lower()
|
||
|
||
unit_text = f'''[Unit]
|
||
Description={game}: Server
|
||
Wants=network-online.target
|
||
After=syslog.target network.target nss-lookup.target network-online.target
|
||
|
||
[Service]
|
||
ExecStartPre=/usr/bin/steamcmd +force_install_dir {unit_dir_server} +login anonymous +app_update {id_game} +quit
|
||
TimeoutStartSec=99999
|
||
ExecStart={systemd_unit_exec}
|
||
LimitNOFILE=100000
|
||
ExecReload=/bin/kill -s HUP $MAINPID
|
||
ExecStop=/bin/kill -s INT $MAINPID
|
||
|
||
[Install]
|
||
WantedBy=default.target
|
||
'''
|
||
with open(unit_file, 'w') as systemd_unit:
|
||
systemd_unit.write(unit_text)
|
||
unit_name = unit_file.split("/")[-1]
|
||
os.system(f"systemctl --user unmask {unit_name}")
|
||
os.system('systemctl --user daemon-reload')
|
||
os.system(f"systemctl --user enable {unit_name}")
|
||
|
||
|
||
@hlna.command(help='Скачивание и установка модов <hlna ark -m all -i 111111111>')
|
||
@click.argument('g', nargs=1)
|
||
@click.option('-m', default='all', help="Название карты для запуска или all для запуска всех карт")
|
||
@click.option("-i/-u", default=True, help="-i установить моды, -u удалить моды")
|
||
@click.argument('id_mods_ark', nargs=-1)
|
||
def mod(g, m, i, id_mods_ark):
|
||
if g == "ark":
|
||
id_game_workshop = "346110"
|
||
if not os.path.isdir(dir_mods_ark):
|
||
create_dir(dir_mods_ark)
|
||
id_mods_ark = id_mods_ark[0].split(',')
|
||
for id_mod in id_mods_ark:
|
||
dir_ark_mods = f"{dir_mods_ark}/{id_mod}"
|
||
if i:
|
||
os.system(f"steamcmd +login anonymous +workshop_download_item {id_game_workshop} {id_mod} +quit")
|
||
modextract(id_mod, id_game_workshop, dir_ark_mods)
|
||
else:
|
||
os.system(f"rm -rf {dir_ark_mods}")
|
||
print_line(f"{dir_ark_mods} удалён")
|
||
os.system(f"rm {dir_mods_ark}/{id_mod}.mod")
|
||
print_line(f"{dir_mods_ark}/{id_mod}.mod удалён")
|
||
|
||
|
||
def modextract(id_mod, id_game_workshop, dir_ark_mods):
|
||
"""Распаковывает файлы мода и создаёт .mod файл для него"""
|
||
dir_steam_workshop = f"{dir_workshop_ark}/content/{id_game_workshop}/{id_mod}/WindowsNoEditor"
|
||
dir_extract = dir_ark_mods
|
||
if id_mod == "111111111":
|
||
return
|
||
try:
|
||
for curdir, subdirs, files in os.walk(os.path.join(dir_steam_workshop)):
|
||
for file in files:
|
||
name, ext = os.path.splitext(file)
|
||
if ext == ".z":
|
||
src = os.path.join(curdir, file)
|
||
dst = os.path.join(curdir, name)
|
||
uncompressed = os.path.join(curdir, file + ".uncompressed_size")
|
||
unpack(src, dst)
|
||
print("[+] Extracted " + file)
|
||
os.remove(src)
|
||
if os.path.isfile(uncompressed):
|
||
os.remove(uncompressed)
|
||
except Exception as e:
|
||
print(e)
|
||
print("[x] Unpacking .z files failed, aborting mod install")
|
||
return False
|
||
|
||
os.system(f"rm -rf {dir_ark_mods}")
|
||
os.system(f"mv -f {dir_steam_workshop} {dir_ark_mods}")
|
||
|
||
modname = subprocess.check_output(['curl', '-s', f'https://steamcommunity.com/sharedfiles/filedetails/?id={id_mod}']).decode('utf-8')
|
||
modname = re.search(r'<div class="workshopItemTitle">(.+)</div>', modname)
|
||
modname = modname and modname.group(1)
|
||
|
||
if os.path.isfile(f"{dir_ark_mods}.mod"):
|
||
os.remove(f"{dir_ark_mods}.mod")
|
||
|
||
with open(f"{dir_extract}/mod.info", "rb") as modinfo:
|
||
data = modinfo.read()
|
||
mapnamelen = struct.unpack_from("<L", data, 0)[0]
|
||
mapname = data[4:mapnamelen + 3]
|
||
nummaps = struct.unpack_from("<L", data, mapnamelen + 4)[0]
|
||
pos = mapnamelen + 8
|
||
modname = (modname.encode() or mapname.decode()) + b'\x00'
|
||
modnamelen = len(modname)
|
||
modpath = b"../../../" + dir_shooter.encode() + b"/Content/Mods/" + id_mod.encode() + b'\x00'
|
||
modpathlen = len(modpath)
|
||
with open(f"{dir_ark_mods}.mod", "wb") as mod:
|
||
mod.write(struct.pack(f'<LLL{modnamelen}sL{modpathlen}sL', int(id_mod), 0, modnamelen, modname,
|
||
modpathlen, modpath, nummaps))
|
||
for mapnum in range(nummaps):
|
||
mapfilelen = struct.unpack_from("<L", data, pos)[0]
|
||
mapfile = data[mapnamelen + 12:mapnamelen + 12 + mapfilelen]
|
||
mod.write(struct.pack("<L%ds" % mapfilelen, mapfilelen, mapfile))
|
||
pos = pos + 4 + mapfilelen
|
||
mod.write(b"\x33\xFF\x22\xFF\x02\x00\x00\x00\x01")
|
||
|
||
if os.path.isfile(os.path.join(dir_extract, "modmeta.info")):
|
||
with open(os.path.join(dir_extract, "modmeta.info"), "rb") as f:
|
||
with open(f"{dir_extract}.mod", "ab") as f_out:
|
||
f_out.write(f.read())
|
||
else:
|
||
with open(f"{dir_mods_ark}.mod", "wb") as f_out:
|
||
f_out.write(b'\x01\x00\x00\x00\x08\x00\x00\x00ModType\x00\x02\x00\x00\x001\x00')
|
||
|
||
if dir_extract != dir_ark_mods:
|
||
if not os.path.isdir(dir_ark_mods):
|
||
os.makedirs(dir_ark_mods)
|
||
|
||
|
||
@hlna.command(help='Выключение/включение серверов (без удаления) <hlna switch -m all -d')
|
||
@click.option("-m", required=True, help="Название cервера")
|
||
@click.option("-e/-d", default=True, help="-e активировать карты, -d деактивировать")
|
||
def switch(m, e):
|
||
m = m.split(",")
|
||
if not os.path.isdir(dir_deactivated):
|
||
create_dir(dir_deactivated)
|
||
if e:
|
||
port_s = []
|
||
query_p = []
|
||
for k in list_config:
|
||
data = read_yaml(k)
|
||
port_s.append(data['Port'])
|
||
query_p.append(data['QueryPort'])
|
||
for i in m:
|
||
try:
|
||
if i in list_config:
|
||
print(f"Карта {i} уже есть в активных")
|
||
continue
|
||
data = read_yaml(i, False)
|
||
if data['Port'] in port_s:
|
||
print("Предлагаем заменить")
|
||
continue
|
||
if data['QueryPort'] in query_p:
|
||
print("Заменить query port?")
|
||
continue
|
||
x = os.system(
|
||
f"mv {dir_deactivated}{i} {dir_maps_ark} >> {dir_logs}{date} 2>&1")
|
||
os.system(f"systemctl --user stop ark_{i}")
|
||
os.system(f"systemctl --user disable ark_{i}")
|
||
with open(f"{dir_logs}{date}.log", "a") as f:
|
||
f.write(f"[{time}] File {i} has been moved to {dir_maps_ark}\n")
|
||
if x == 0:
|
||
print(f"Карта активирована - {i}")
|
||
else:
|
||
print(f"{i} либо уже активирована, либо такой карты нет")
|
||
except:
|
||
print("ошибка при активации карты")
|
||
else:
|
||
for i in m:
|
||
try:
|
||
if i in delist_config:
|
||
print(f"Карта {i} уже есть в деактивированных")
|
||
continue
|
||
x = os.system(
|
||
f"mv {dir_maps_ark}{i} {dir_deactivated} >> {dir_logs}{date} 2>&1")
|
||
os.system(f"systemctl --user enable ark_{i}")
|
||
os.system(f"systemctl --user start ark_{i}")
|
||
with open(f"{dir_logs}{date}.log", "a") as f:
|
||
f.write(f"[{time}] File {i} has been moved to {dir_deactivated}\n")
|
||
if x == 0:
|
||
print(f"Карта деактивирована - {i}")
|
||
else:
|
||
print(f"{i} либо деактивирована, либо такой карты нет")
|
||
except:
|
||
print("ошибка при деактивации карты")
|
||
|
||
|
||
@hlna.command(help='Выводит статус настроеных серверов')
|
||
def status(list_config=list_config):
|
||
if list_config == [] and delist_config == []:
|
||
print_line("Сервера не сконфигурированы")
|
||
else:
|
||
for i in list_config:
|
||
data = read_yaml(i, game="ARK")
|
||
x = os.system(f"lsof -w -i :{data['Port']}")
|
||
if x == 0:
|
||
print(colorama.Fore.GREEN + "Сервер запущен" + colorama.Style.RESET_ALL)
|
||
else:
|
||
print(colorama.Fore.RED + "Сервер не запущен" + colorama.Style.RESET_ALL)
|
||
print(f"""
|
||
Имя сервера: {i}
|
||
Карта: {data['map']}
|
||
Моды: {data['ModsId']}
|
||
Пароль: {data['ServerPassword']}S
|
||
Кластер: {data['Cluster']}
|
||
Кластер id: {data['clusterid']}
|
||
Query порт: {data['QueryPort']}
|
||
Порт сервера: {data['Port']}
|
||
Rcon включен: {data['RCONEnabled']}
|
||
Rcon порт : {data['RCONPort']}
|
||
Максимальное кол-во игроков: {data['MaxPlayers']}""")
|
||
print("-" * 40)
|
||
|
||
if delist_config != []:
|
||
x = input("Есть неактивные сервера, показать Y/n: ")
|
||
if x != "n":
|
||
for i in delist_config:
|
||
data = read_yaml(i, False)
|
||
print(f"""
|
||
Имя сервера: {i}
|
||
Карта: {data['map']}
|
||
Моды: {data['ModsId']}
|
||
Пароль: {data['ServerPassword']}
|
||
Кластер: {data['Cluster']}
|
||
Кластер id: {data['clusterid']}
|
||
Query порт: {data['QueryPort']}
|
||
Порт сервера: {data['Port']}
|
||
Rcon включен: {data['RCONEnabled']}
|
||
Rcon порт : {data['RCONPort']}
|
||
Максимальное кол-во игроков: {data['MaxPlayers']}""")
|
||
print("-" * 40)
|
||
|
||
|
||
@hlna.command(help='Запуск, сконфигурированного сервера или кластера <hlna start -g ark -m all>')
|
||
@click.option('-g', required=True, help="Название игры для запуска. (ark, 7days")
|
||
@click.option('-m', default='all', help="Название карты для запуска или all для запуска все карт")
|
||
def start(g, m):
|
||
"""Запускает сервер выбранной игры"""
|
||
# добавить проверку на ввод аргумента ark/7day если else: давать подсказку
|
||
# если нет конфигов, то выводим что серверов нет
|
||
start_stop("start", g, m)
|
||
|
||
|
||
@hlna.command(help='Остановка, сконфигурированного сервера или кластера <hlna stop -g ark -m all>')
|
||
@click.option('-g', required=True, help="Название игры для запуска. (ark, 7days")
|
||
@click.option('-m', default='all', help="Название карты для запуска или all для запуска все карт")
|
||
def stop(g, m):
|
||
|
||
start_stop("stop", g, m)
|
||
|
||
|
||
@hlna.command(help='Перезапуск, сконфигурированного сервера или кластера <hlna restart -g ark -m all>')
|
||
@click.option('-g', required=True, help="Название игры для запуска. (ark, 7days")
|
||
@click.option('-m', default='all', help="Название карты для запуска или all для запуска все карт")
|
||
def restart(g, m):
|
||
start_stop("restart", g, m)
|
||
|
||
|
||
def check_exist_servers(g):
|
||
"""Проверяет наличие конфигов для активных карт"""
|
||
if g == "ark":
|
||
if not os.path.exists(f"{dir_mods_ark}"):
|
||
print_line("Нет сконфигурированных серверов") # добавить отсюда вилку на вопрос с конфигурацией
|
||
else:
|
||
return
|
||
elif g == "7days":
|
||
print_line("7Days")
|
||
|
||
|
||
def start_stop(action, g, m, list_config=list_config):
|
||
"""Функция изменения статусов сервера"""
|
||
if g != "ark" or "7days":
|
||
return
|
||
elif g == "ark":
|
||
check_exist_servers(g)
|
||
dict_mapname = {}
|
||
dict_allmapname = []
|
||
for i in list_config:
|
||
data = read_yaml(i, game="ARK")
|
||
dict_mapname[data['SessionName']] = data['map']
|
||
dict_allmapname.append(data['SessionName'])
|
||
names_serverstart = []
|
||
for ns, v in dict_mapname.items():
|
||
if v in m:
|
||
names_serverstart.append(ns)
|
||
if list_config != []: # Перенести выше для проверки наличия конфигов
|
||
if m == "all":
|
||
names_serverstart = dict_allmapname
|
||
print(f"Выполняется для карт(-ы) {names_serverstart}")
|
||
else:
|
||
names_serverstart = choose_map(names_serverstart)
|
||
for i in names_serverstart:
|
||
data = read_yaml(i, game="ARK")
|
||
y = os.system(
|
||
f"~/git/hln-a/hlna.py rcon SaveWorld -m {i}") if action == "restart" or action == "stop" else ""
|
||
x = os.system(f"systemctl --user {action} ark_{data['SessionName'].lower()}.service")
|
||
if x == 0:
|
||
print_line("Готово")
|
||
elif g == "7days":
|
||
x = os.system(f"systemctl --user {action} 7days.service")
|
||
if x == 0:
|
||
print_line("Готово")
|
||
|
||
|
||
def read_yaml(list_config=list_config, flag=True, game=""):
|
||
"""Читает конфиги и отдаёт данные туда где их запросили"""
|
||
# Читаем конфиги активных или неактивных карт в зависимости от флага
|
||
if game == "ARK":
|
||
path_yaml = f"{dir_maps_ark}{list_config}" if flag else f"{dir_deactivated}{list_config}"
|
||
elif game == "path_server":
|
||
path_yaml = dir_config + "config"
|
||
with open(path_yaml, "r") as yamlfile:
|
||
data = yaml.load(yamlfile, Loader=yaml.FullLoader)
|
||
return data[0] # возвращаем словарь со всеми значениями
|
||
|
||
|
||
def choose_map(arr):
|
||
"""Функция выбора карт"""
|
||
new_arr = []
|
||
arr = sorted(arr)
|
||
print('Найдены сервера с этой картой')
|
||
for i, map in enumerate(arr):
|
||
print(f"{i + 1}) {map}")
|
||
while True:
|
||
try:
|
||
x = input("Выберите сервер из списка, либо несколько через запятую: ").split(',')
|
||
x = [int(i) for i in x]
|
||
break
|
||
except:
|
||
print("Неправильный ввод")
|
||
|
||
for i in x:
|
||
new_arr.append(arr[i - 1])
|
||
print('Выбранные сервера:', new_arr)
|
||
|
||
return new_arr
|
||
|
||
|
||
@hlna.command(help='Отправка команд на игровой сервер через rcon <rcon SaveWorld -m all>')
|
||
@click.argument('c', nargs=1)
|
||
@click.option('-m', required=True, help="Название карты для применения rcon команды")
|
||
def rcon(m, c):
|
||
dict_mapname = {}
|
||
dict_adminpwd = {}
|
||
if list_config:
|
||
rcon_ports = []
|
||
for i in list_config:
|
||
data = read_yaml(i, game="ARK")
|
||
dict_mapname[data['RCONPort']] = data['map']
|
||
dict_adminpwd[data['RCONPort']] = data['ServerAdminPassword']
|
||
if m == "all":
|
||
for rcon_p in dict_mapname:
|
||
rcon_ports.append(rcon_p)
|
||
else:
|
||
for rcon_p, name_map in dict_mapname.items():
|
||
if name_map in m:
|
||
rcon_ports.append(rcon_p)
|
||
print_line(f"Карта которая запускается {name_map}")
|
||
for port in rcon_ports:
|
||
print(f"Rcon выполнен для {port}")
|
||
passwd = dict_adminpwd[port]
|
||
with Client('127.0.0.1', port, passwd=str(passwd)) as client:
|
||
response = client.run(c)
|
||
print(response)
|
||
else:
|
||
pass
|
||
|
||
|
||
def zero(x=""):
|
||
"""Потом пригодится"""
|
||
return ""
|
||
|
||
|
||
if not os.path.exists(dir_config + "config"):
|
||
dir_server = path_server()
|
||
else:
|
||
data = read_yaml(game="path_server")
|
||
if data['path_server'] == "":
|
||
path_server()
|
||
else:
|
||
dir_server = data['path_server']
|
||
|
||
dir_unit = f"{home_dir}/.config/systemd/user/"
|
||
dir_logs = f"{dir_config}logs/"
|
||
|
||
dir_server_ark = f"{dir_server}ARK/"
|
||
dir_server_exec = f"{dir_server_ark}ShooterGame/Binaries/Linux/"
|
||
dir_workshop_ark = f"{home_dir}/.local/share/Steam/steamapps/workshop"
|
||
dir_shooter = "ShooterGame"
|
||
dir_mods_ark = f"{dir_server_ark}ShooterGame/Content/Mods"
|
||
|
||
dir_server_7days = f"{dir_server}/7Days/"
|
||
|
||
now = datetime.datetime.now()
|
||
date = now.strftime("%Y-%m-%d")
|
||
time = now.strftime("%H:%M:%S")
|
||
create_dir(dir_server)
|
||
create_dir(dir_unit)
|
||
create_dir(dir_logs)
|
||
|
||
if __name__ == '__main__':
|
||
hlna()
|