-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlaunchcs.py
executable file
·64 lines (56 loc) · 2.89 KB
/
launchcs.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/python3
from subprocess import run as runCommand
import pathlib
import argparse
INSTANCES_PATH = "/home/cs-servers/msm.d/cs2"
def main() -> None:
arguments = initializeParser()
args = arguments.parse_args()
action = args.action
numberOfServer = args.numberOfServer
servers = getServerList()
runningServers = getRunningServers(servers)
stoppedServers = [server for server in servers if runningServers == [] or server not in runningServers]
match action:
case "start":
if numberOfServer > len(stoppedServers):
print(f"Can't launch this much servers, {len(servers)} are found and {len(runningServers)} are running!")
return
elif numberOfServer == 0:
print("Please specify the number of server to start")
return
for server,_ in zip(stoppedServers, range(numberOfServer)):
launchServer(server)
print("Start successfully !")
case "stop":
if numberOfServer > len(runningServers):
print(f"Can't stop launch this much servers, {len(runningServers)} are running out of the {len(servers)} found")
return
elif numberOfServer == 0:
print("Please specify the number of server to stop")
return
for server,_ in zip(reversed(runningServers), range(numberOfServer)):
closeServer(server)
print("Stop successfully !")
case "list":
print("Servers found:")
for server in servers:
print(f" - {server} {'(running)' if server in runningServers else '(stopped)'}")
case _:
print("Invalid action, please use 'start' or 'stop', here is the help:")
arguments.print_help()
def initializeParser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(prog="launchcs" ,description="Launch or stop a number of CS2 servers", usage="%(prog)s action numberOfServer")
parser.add_argument("action", type=str, choices=["start", "stop", "list"], help="The action to perform, either 'start', 'stop', or 'list'")
parser.add_argument("numberOfServer", type=int, nargs='?', default=0, help="The number of server to start or stop")
return parser
def getServerList() -> list[str]:
return [f.name[5:] for f in sorted(pathlib.Path(INSTANCES_PATH).iterdir(), key=lambda f: (len(f.name), f.name)) if f.is_dir() and f.name.startswith("inst")]
def launchServer(server: str) -> None:
runCommand(f"cs2-server @{server} start", shell=True)
def closeServer(server: str) -> None:
runCommand(f"cs2-server @{server} stop", shell=True)
def getRunningServers(serverList: list[str]) -> list[str]:
return [server for server in serverList if b"STOPPED" not in runCommand(f"cs2-server @{server} status", shell=True, capture_output=True).stdout]
if __name__ == "__main__":
main()