Revert "change if else and fix function servers"
This reverts commit d4eece79e3a7f904a5424a98c68b626c8075ec1a.
This commit is contained in:
parent
fdccb54b45
commit
cbecbcecda
0
LICENSE.md
Executable file → Normal file
0
LICENSE.md
Executable file → Normal file
0
README.md
Executable file → Normal file
0
README.md
Executable file → Normal file
190
hlna.py
190
hlna.py
@ -1,23 +1,28 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import time
|
||||
import threading
|
||||
|
||||
from pathlib import Path
|
||||
from pprint import pprint
|
||||
import datetime
|
||||
|
||||
import yaml
|
||||
import click
|
||||
import colorama
|
||||
import click_completion
|
||||
|
||||
from pathlib import Path
|
||||
from rcon.source import Client
|
||||
|
||||
home_dir = Path.home()
|
||||
dir_server = f"{home_dir}/ARK_Servers/"
|
||||
dir_config = f"{home_dir}/.config/hlna/maps/"
|
||||
dir_server = f"{home_dir}/Servers/"
|
||||
dir_server_ark = f"{dir_server}/ARK/"
|
||||
server_dir = f"{dir_server_ark}ShooterGame/Binaries/Linux/"
|
||||
dir_unit = f"{home_dir}/.config/systemd/user/"
|
||||
dir_config = f"{home_dir}/.config/hlna/"
|
||||
dir_logs = f"{dir_config}logs/"
|
||||
dir_maps = f"{dir_config}maps/"
|
||||
dir_deactivated = f"{dir_maps}deactivated/"
|
||||
|
||||
mods_id = ""
|
||||
listen_server = True
|
||||
now = datetime.datetime.now()
|
||||
date = now.strftime("%Y-%m-%d")
|
||||
time = now.strftime("%H:%M:%S")
|
||||
|
||||
|
||||
@click.group()
|
||||
@ -25,6 +30,20 @@ def hlna():
|
||||
pass
|
||||
|
||||
|
||||
def create_dir(directory):
|
||||
"""Проверка и создание директории"""
|
||||
if not os.path.exists(directory):
|
||||
os.mkdir(directory)
|
||||
|
||||
|
||||
create_dir(dir_server)
|
||||
create_dir(dir_server_ark)
|
||||
create_dir(dir_unit)
|
||||
create_dir(dir_config)
|
||||
create_dir(dir_logs)
|
||||
create_dir(dir_maps)
|
||||
|
||||
|
||||
def find_file(path):
|
||||
"""Находим все конфиги в зависимости от пути"""
|
||||
arr = next(os.walk(path), (None, None, []))[2] # [] if no file
|
||||
@ -37,8 +56,8 @@ def find_file(path):
|
||||
return arr
|
||||
|
||||
|
||||
list_config = find_file(dir_config)
|
||||
delist_config = find_file(dir_config+"deactivated")
|
||||
list_config = find_file(dir_maps)
|
||||
delist_config = find_file(dir_deactivated)
|
||||
|
||||
|
||||
def print_line(text):
|
||||
@ -48,17 +67,6 @@ def print_line(text):
|
||||
print(colorama.Fore.YELLOW + "-" * 30 + colorama.Style.RESET_ALL)
|
||||
|
||||
|
||||
def create_dir(directory):
|
||||
"""Проверка и создание директории"""
|
||||
if not os.path.exists(directory):
|
||||
os.mkdir(directory)
|
||||
if not os.path.exists(f"{home_dir}/.config/hlna/"):
|
||||
os.chdir(f"{home_dir}/.config/")
|
||||
os.mkdir("hlna")
|
||||
if not os.path.exists(f"{home_dir}/.config/hlna/maps"):
|
||||
os.chdir(f"{home_dir}/.config/hlna/")
|
||||
os.mkdir("maps")
|
||||
|
||||
def check_int(number=""):
|
||||
"""Проверка на ввод числа"""
|
||||
while True:
|
||||
@ -69,15 +77,24 @@ def check_int(number=""):
|
||||
x = int(x)
|
||||
return x
|
||||
except ValueError:
|
||||
print("Введите число")
|
||||
print_line("Введите число")
|
||||
|
||||
|
||||
create_dir(dir_server)
|
||||
create_dir(dir_config)
|
||||
@hlna.command(help='Сбор настроек для сервера или кластера')
|
||||
def config():
|
||||
while True:
|
||||
count_server = check_int("""Выберите игру для конфигурирования
|
||||
1. ARK Survival Evolved
|
||||
: """)
|
||||
if count_server == 1:
|
||||
config_ark()
|
||||
break
|
||||
else:
|
||||
print_line("Пока есть только ARK xD")
|
||||
|
||||
|
||||
@hlna.command(help='Для конфигурирования параметров запускаемого сервера или кластера серверов')
|
||||
def config(list_config=list_config):
|
||||
def config_ark(list_config=list_config):
|
||||
"""Сбор данных для конфига"""
|
||||
data = {}
|
||||
port_s = []
|
||||
rcon_p = []
|
||||
@ -90,7 +107,6 @@ def config(list_config=list_config):
|
||||
1. Да
|
||||
2. Нет
|
||||
: """)
|
||||
|
||||
if count_cluster == 1:
|
||||
cluster_server = True
|
||||
cluster_id = input("Укажите id для кластера, любое сочетание символов: \n")
|
||||
@ -104,7 +120,6 @@ def config(list_config=list_config):
|
||||
for i in list_config:
|
||||
data = read_yaml(i)
|
||||
print(f"{i} : {data['map']}")
|
||||
# id_srv[data['SessionName']] = data['id_server']
|
||||
|
||||
count_maps = check_int("Укажите количество карт: \n")
|
||||
if count_maps == 0: # 0 возвращает check_int когда, ничего не было введено
|
||||
@ -113,8 +128,6 @@ def config(list_config=list_config):
|
||||
for i in range(count_maps):
|
||||
while True:
|
||||
"Проверка на выбор карты из списка"
|
||||
|
||||
# os.system("clear")
|
||||
amount_map = check_int("""Выберите карту из списка указав номер
|
||||
1. The Island
|
||||
2. The Center
|
||||
@ -184,7 +197,6 @@ def config(list_config=list_config):
|
||||
|
||||
if list_config:
|
||||
data = read_yaml(list_config[-1])
|
||||
|
||||
while True:
|
||||
name_server = input("Укажите название Сервера: \n")
|
||||
if name_server == "":
|
||||
@ -194,7 +206,6 @@ def config(list_config=list_config):
|
||||
while new_name in list_config:
|
||||
new_name = f"{map_s}{str(count)}"
|
||||
count += 1
|
||||
|
||||
list_config.append(new_name)
|
||||
print(list_config)
|
||||
break
|
||||
@ -203,20 +214,19 @@ def config(list_config=list_config):
|
||||
break
|
||||
else:
|
||||
if name_server in list_config:
|
||||
print("Имя занято")
|
||||
print_line("Имя занято")
|
||||
else:
|
||||
list_config.append(name_server) # если enter, то ставим последним элементом карту
|
||||
break
|
||||
|
||||
print("Укажите порт сервера:\n")
|
||||
port_server = ports(port_s)
|
||||
print("Укажите query порт сервера:\n")
|
||||
query_port = ports(query_p)
|
||||
|
||||
if port_server == 0:
|
||||
port_server = 7777
|
||||
if query_port == 0:
|
||||
query_port = 27015
|
||||
|
||||
print("Порт Сервера=", port_server)
|
||||
print("Query Port=", query_port)
|
||||
|
||||
@ -232,10 +242,24 @@ def config(list_config=list_config):
|
||||
if max_players == 0:
|
||||
max_players = 70
|
||||
|
||||
yaml_create(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)
|
||||
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(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 yaml_create(cluster_server, map_s, name_server, port_server, query_port, rcon_enabled, rcon_port, adminpassword_server, password_server, max_players, cluster_id, cluster_dir_override):
|
||||
def yaml_create(cluster_server, map_s, name_server, port_server, query_port, rcon_enabled, rcon_port,
|
||||
adminpassword_server, password_server, max_players, cluster_id, cluster_dir_override, listen_server):
|
||||
settings_hlna = [
|
||||
{
|
||||
'map': map_s,
|
||||
@ -255,9 +279,41 @@ def yaml_create(cluster_server, map_s, name_server, port_server, query_port, rco
|
||||
'clusterdir': cluster_dir_override
|
||||
}
|
||||
]
|
||||
with open(dir_config + f"{name_server}", 'w') as yamlfile:
|
||||
with open(dir_maps + f"{name_server}", 'w') as yamlfile:
|
||||
yaml.dump(settings_hlna, yamlfile)
|
||||
print(colorama.Fore.GREEN + "Конфиг создан" + colorama.Style.RESET_ALL)
|
||||
systemd_unit_create()
|
||||
|
||||
|
||||
def systemd_unit_create(name_server=list_config):
|
||||
for i in name_server:
|
||||
data = read_yaml(i)
|
||||
if not data['Cluster']:
|
||||
ntff = ""
|
||||
else:
|
||||
ntff = "-NoTransferFromFiltering"
|
||||
unit_file = f"{dir_unit}ARK_{data['SessionName']}.service"
|
||||
unit_text = f'''[Unit]
|
||||
Description=ARK: Survival Evolved dedicated server - {data['map']}
|
||||
Wants=network-online.target
|
||||
After=syslog.target network.target nss-lookup.target network-online.target
|
||||
|
||||
[Service]
|
||||
ExecStartPre=/usr/bin/steamcmd +force_install_dir {dir_server} +login anonymous +app_update 376030 +quit
|
||||
TimeoutStartSec=1200
|
||||
ExecStart={dir_server_ark}ShooterGameServer {data['map']}?listen={data['Listen']}?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}
|
||||
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)
|
||||
os.system(f"systemctl --user unmask ARK_{data['SessionName']}.service")
|
||||
os.system(f"systemctl --user enable ARK_{data['SessionName']}.service")
|
||||
os.system('systemctl --user daemon-reload')
|
||||
|
||||
|
||||
def test_mod_install():
|
||||
@ -278,10 +334,11 @@ test_mod_install()
|
||||
@click.option("-m", required=True, help="Название Сервера")
|
||||
@click.option("-e/-d", default=True, help="-e активировать карты, -d деактивировать")
|
||||
def enablemap(m, e):
|
||||
"""Тут переписать надо"""
|
||||
"""Включение/выключение карт"""
|
||||
|
||||
m = m.split(",")
|
||||
# m = check_name_map(m, False)
|
||||
create_dir(dir_config + "deactivated")
|
||||
if not os.path.isdir(dir_deactivated):
|
||||
create_dir(dir_deactivated)
|
||||
if e == True:
|
||||
port_s = []
|
||||
query_p = []
|
||||
@ -297,24 +354,32 @@ def enablemap(m,e):
|
||||
data = read_yaml(i)
|
||||
if data['Port'] in port_s:
|
||||
print("Предлагаем заменить")
|
||||
continue
|
||||
if data['QueryPort'] in query_p:
|
||||
print("Заменить query port?")
|
||||
x = os.system(f"mv {dir_config}deactivated/{i} {dir_config + i} 2>> {dir_config}logs") #Добавить текущее время
|
||||
continue
|
||||
x = os.system(f"mv {dir_deactivated}{i} {dir_maps} >> {dir_logs}{date} 2>&1") # Добавить текущее время
|
||||
with open(f"{dir_logs}{date}.log", "a") as f:
|
||||
f.write(f"[{time}] File {i} has been moved to {dir_maps}\n")
|
||||
if x == 0:
|
||||
print(f"Карта активирована - {i}")
|
||||
else:
|
||||
print(f"{i} либо уже активирована, либо такой карты нет")
|
||||
except:
|
||||
print("ошибка")
|
||||
finally:
|
||||
pass
|
||||
# except:
|
||||
# print("ошибка при активации карты")
|
||||
# pass
|
||||
else:
|
||||
|
||||
for i in m:
|
||||
try:
|
||||
if i in delist_config:
|
||||
print(f"Карта {i} уже есть в деактивированных")
|
||||
continue
|
||||
x = os.system(f"mv {dir_config + i} {dir_config}deactivated/{i} 2>> {dir_config}logs") #Добавить текущее время
|
||||
x = os.system(
|
||||
f"mv {dir_maps}{i} {dir_deactivated} >> {dir_logs}{date} 2>&1") # Добавить текущее время
|
||||
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:
|
||||
@ -396,36 +461,19 @@ def start(m, b, name_server=list_config):
|
||||
else:
|
||||
names_serverstart = choose_map(names_serverstart)
|
||||
|
||||
server_dir = dir_server + "ShooterGame/Binaries/Linux/"
|
||||
print_line("Валидация файлов сервера")
|
||||
x = os.system(f"steamcmd +force_install_dir {dir_server} +login anonymous +app_update 376030 +quit")
|
||||
os.chdir(server_dir)
|
||||
for i in names_serverstart:
|
||||
data = read_yaml(i)
|
||||
starting_map = dict_mapname[i]
|
||||
print_line(data['Cluster'])
|
||||
ntff = '' if not data['Cluster'] else "-NoTransferFromFiltering"
|
||||
def starting(i):
|
||||
os.system(f"{server_dir}ShooterGameServer {i}?SessionName={data['SessionName']}?Port={data['Port']}\
|
||||
?QueryPort={data['QueryPort']}?RCONEnabled={data['RCONEnabled']}?RCONPort={data['RCONPort']}\
|
||||
?ServerAdminPassword={data['ServerAdminPassword']}?MaxPlayers={data['MaxPlayers']}\
|
||||
?GameModIds={data['ModsId']}?listen={data['Listen']} -clusterid={data['clusterid']}\
|
||||
-ClusterDirOverride={data['clusterdir']} {ntff}")
|
||||
if x == 0:
|
||||
print_line("Запускаем карту" + i)
|
||||
threads = threading.Thread(target=starting, args=(starting_map,))
|
||||
threads.start()
|
||||
else:
|
||||
print(f"Карта не запущена, сервер не установлен")
|
||||
|
||||
os.system(f"systemctl --user start ARK_{data['SessionName']}.service")
|
||||
else:
|
||||
print("Ни одной карты не установлено")
|
||||
|
||||
|
||||
def read_yaml(name_server, flag=True):
|
||||
def read_yaml(list_config, flag=True):
|
||||
# Читаем конфиги активных или неактивных карт в зависимости от флага
|
||||
dirs = f"{dir_config}{name_server}" if flag else f"{dir_config}deactivated/{name_server}"
|
||||
|
||||
if flag:
|
||||
dirs = f"{dir_maps}{list_config}"
|
||||
else:
|
||||
dirs = f"{dir_deactivated}{list_config}"
|
||||
with open(dirs, "r") as yamlfile:
|
||||
data = yaml.load(yamlfile, Loader=yaml.FullLoader)
|
||||
return data[0] # возвращаем словарь со всеми значениями
|
||||
@ -482,7 +530,5 @@ def zero(x=""):
|
||||
return ""
|
||||
|
||||
|
||||
# if __name__ == 'hlna':
|
||||
# input = zero
|
||||
if __name__ == '__main__':
|
||||
hlna()
|
||||
|
0
hlna_discord_bot.py
Executable file → Normal file
0
hlna_discord_bot.py
Executable file → Normal file
0
logo.png
Executable file → Normal file
0
logo.png
Executable file → Normal file
Before Width: | Height: | Size: 30 KiB After Width: | Height: | Size: 30 KiB |
0
pytest.py
Executable file → Normal file
0
pytest.py
Executable file → Normal file
Loading…
Reference in New Issue
Block a user