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
276
hlna.py
276
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,28 +56,17 @@ 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):
|
||||
"""Добавление тире вокруг текста, покраска"""
|
||||
print(colorama.Fore.YELLOW + "-"*30)
|
||||
print(colorama.Fore.YELLOW + "-" * 30)
|
||||
print(f"{colorama.Fore.GREEN} + {text}")
|
||||
print(colorama.Fore.YELLOW + "-"*30 + colorama.Style.RESET_ALL)
|
||||
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,28 +77,36 @@ 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 = []
|
||||
query_p = []
|
||||
|
||||
|
||||
cluster_id = ""
|
||||
cluster_dir_override = ""
|
||||
|
||||
|
||||
count_cluster = check_int("""Укажите требуется ли кластер?
|
||||
1. Да
|
||||
2. Нет
|
||||
: """)
|
||||
|
||||
if count_cluster == 1:
|
||||
cluster_server = True
|
||||
cluster_id = input("Укажите id для кластера, любое сочетание символов: \n")
|
||||
@ -104,17 +120,14 @@ 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 когда, ничего не было введено
|
||||
count_maps = 1
|
||||
|
||||
|
||||
for i in range(count_maps):
|
||||
while True:
|
||||
"Проверка на выбор карты из списка"
|
||||
|
||||
# os.system("clear")
|
||||
amount_map = check_int("""Выберите карту из списка указав номер
|
||||
1. The Island
|
||||
2. The Center
|
||||
@ -180,11 +193,10 @@ def config(list_config=list_config):
|
||||
if port in ports_arr:
|
||||
print("Порт уже занят")
|
||||
else:
|
||||
return port
|
||||
|
||||
return port
|
||||
|
||||
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)
|
||||
|
||||
@ -231,41 +241,87 @@ def config(list_config=list_config):
|
||||
max_players = check_int("Укажите максимальное количество игроков: \n")
|
||||
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,
|
||||
'Cluster' : cluster_server,
|
||||
'SessionName' : name_server,
|
||||
'Port' : port_server,
|
||||
'QueryPort' : query_port,
|
||||
'RCONEnabled' : rcon_enabled,
|
||||
'RCONPort' : rcon_port,
|
||||
'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' : mods_id,
|
||||
'Listen' : listen_server,
|
||||
'ServerPath' : dir_server,
|
||||
'clusterid' : cluster_id,
|
||||
'clusterdir' : cluster_dir_override
|
||||
'ServerPassword': password_server,
|
||||
'MaxPlayers': max_players,
|
||||
'ModsId': mods_id,
|
||||
'Listen': listen_server,
|
||||
'ServerPath': dir_server,
|
||||
'clusterid': cluster_id,
|
||||
'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():
|
||||
pathTest = f"{dir_server}ShooterGame/Saved/Config/LinuxServer/"
|
||||
if os.path.exists(pathTest):
|
||||
os.chdir(pathTest)
|
||||
# "Добавить файл в Game.ini, если модов несколько добавляем еще строку ModIDS=<ModId> [ModInstaller] ModIDS=<ModID>"
|
||||
# c этим не разобрался
|
||||
# "Добавить файл в Game.ini, если модов несколько добавляем еще строку ModIDS=<ModId> [ModInstaller] ModIDS=<ModID>"
|
||||
# c этим не разобрался
|
||||
os.system("echo ActiveMods=2943454417 >> GameUserSettings.ini")
|
||||
else:
|
||||
print_line("Сервер не установлен")
|
||||
@ -277,11 +333,12 @@ test_mod_install()
|
||||
@hlna.command()
|
||||
@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")
|
||||
def enablemap(m, e):
|
||||
"""Включение/выключение карт"""
|
||||
|
||||
m = m.split(",")
|
||||
if not os.path.isdir(dir_deactivated):
|
||||
create_dir(dir_deactivated)
|
||||
if e == True:
|
||||
port_s = []
|
||||
query_p = []
|
||||
@ -297,33 +354,41 @@ 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:
|
||||
print(f"{i} либо деактивирована, либо такой карты нет")
|
||||
except:
|
||||
pass
|
||||
|
||||
|
||||
@hlna.command()
|
||||
|
||||
@hlna.command()
|
||||
def servers(map_server=list_config):
|
||||
# Добавить сортивку по кластерам и вывод несколько столбиков
|
||||
if map_server == [] and delist_config == []:
|
||||
@ -349,10 +414,10 @@ def servers(map_server=list_config):
|
||||
Rcon порт : {data['RCONPort']}
|
||||
Максимальное кол-во игроков: {data['MaxPlayers']}""")
|
||||
print("-" * 40)
|
||||
|
||||
if delist_config!=[]:
|
||||
|
||||
if delist_config != []:
|
||||
x = input("Есть неактивные сервера, показать Y/n: ")
|
||||
if x!="n":
|
||||
if x != "n":
|
||||
for i in delist_config:
|
||||
data = read_yaml(i, False)
|
||||
print(f"""
|
||||
@ -368,8 +433,8 @@ def servers(map_server=list_config):
|
||||
Rcon порт : {data['RCONPort']}
|
||||
Максимальное кол-во игроков: {data['MaxPlayers']}""")
|
||||
print("-" * 40)
|
||||
|
||||
|
||||
|
||||
|
||||
@hlna.command(help='Для запуска, сконфигурированного сервера или кластера')
|
||||
@click.option('-m', default='all', help="Название карты для запуска или all для запуска все карт")
|
||||
@click.option('-b', default='', help="")
|
||||
@ -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] # возвращаем словарь со всеми значениями
|
||||
@ -435,27 +483,27 @@ def choose_map(arr):
|
||||
new_arr = []
|
||||
arr = sorted(arr)
|
||||
print('Найдены сервера с этой картой')
|
||||
for i,map in enumerate(arr):
|
||||
print(f"{i+1}) {map}")
|
||||
for i, map in enumerate(arr):
|
||||
print(f"{i + 1}) {map}")
|
||||
while True:
|
||||
try:
|
||||
x = input("Выберите сервер из списка, либо несколько через запятую: ").split(',')
|
||||
x = [int (i) for i in x]
|
||||
x = [int(i) for i in x]
|
||||
break
|
||||
except:
|
||||
print("Неправильный ввод")
|
||||
|
||||
|
||||
for i in x:
|
||||
new_arr.append(arr[i-1])
|
||||
new_arr.append(arr[i - 1])
|
||||
print('Выбранные сервера:', new_arr)
|
||||
|
||||
|
||||
return new_arr
|
||||
|
||||
|
||||
@hlna.command()
|
||||
@click.argument('c', nargs=1)
|
||||
@click.argument('c', nargs=1)
|
||||
@click.option('-m', required=True, help="Название карты для применения rcon команды")
|
||||
def rcon(m,c):
|
||||
def rcon(m, c):
|
||||
print_line("Команда: ", c)
|
||||
print_line("Карты: ", m)
|
||||
dict_mapname = {}
|
||||
@ -466,7 +514,7 @@ def rcon(m,c):
|
||||
dict_adminpwd[data['RCONPort']] = data['ServerAdminPassword']
|
||||
rcon_ports = []
|
||||
for ns, v in dict_mapname.items():
|
||||
print_line(f"переменные v и m {v} & {m}") # обьединить с таким же блоком в start()
|
||||
print_line(f"переменные v и m {v} & {m}") # обьединить с таким же блоком в start()
|
||||
if v in m:
|
||||
rcon_ports.append(ns)
|
||||
print_line(f"Карта которая запускается {ns}")
|
||||
@ -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 ![]() (image error) Size: 30 KiB After ![]() (image error) 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