2024-06-14 21:33:55 +00:00
|
|
|
import subprocess
|
|
|
|
import shlex
|
|
|
|
|
2024-06-20 16:57:04 +00:00
|
|
|
|
2024-06-14 21:33:55 +00:00
|
|
|
class MinecraftServerManager:
|
|
|
|
def __init__(self):
|
|
|
|
self.servers = {}
|
|
|
|
|
|
|
|
def start_server(self, server_directory, java_executable='java', jar_file='server.jar', memory_size='2048M'):
|
|
|
|
command = f"{java_executable} -Xmx{memory_size} -Xms{memory_size} -jar {jar_file} > /dev/null"
|
|
|
|
process = subprocess.Popen(shlex.split(command), cwd=server_directory, stdin=subprocess.PIPE)
|
|
|
|
|
|
|
|
server_id = len(self.servers) + 1
|
|
|
|
self.servers[server_id] = {
|
|
|
|
'process': process,
|
|
|
|
'directory': server_directory,
|
|
|
|
'port': None
|
|
|
|
}
|
2024-06-20 16:57:04 +00:00
|
|
|
|
2024-06-14 21:33:55 +00:00
|
|
|
print(f"Started server {server_id} in directory {server_directory}")
|
|
|
|
return server_id
|
2024-06-20 16:57:04 +00:00
|
|
|
|
2024-06-14 21:33:55 +00:00
|
|
|
def execute_server_command(self, server_id, command):
|
|
|
|
if server_id in self.servers:
|
|
|
|
process = self.servers[server_id]['process']
|
2024-06-24 00:50:08 +00:00
|
|
|
process.stdin.write(command.encode('utf-8') + b'\n')
|
|
|
|
process.stdin.flush()
|
2024-06-14 21:33:55 +00:00
|
|
|
print(f"Server {server_id} executed command : {command}")
|
|
|
|
else:
|
|
|
|
print(f"No server found with ID {server_id}")
|
|
|
|
|
|
|
|
def stop_server(self, server_id):
|
|
|
|
if server_id in self.servers:
|
|
|
|
process = self.servers[server_id]['process']
|
|
|
|
process.communicate(input=b"stop\n")
|
|
|
|
del self.servers[server_id]
|
|
|
|
print(f"Stopped server {server_id}")
|
|
|
|
else:
|
|
|
|
print(f"No server found with ID {server_id}")
|
|
|
|
|
2024-06-20 16:57:04 +00:00
|
|
|
def stop_server_forcefully(self, server_id):
|
2024-06-14 21:33:55 +00:00
|
|
|
if server_id in self.servers:
|
|
|
|
process = self.servers[server_id]['process']
|
|
|
|
process.terminate()
|
|
|
|
del self.servers[server_id]
|
|
|
|
print(f"Stopped server {server_id}")
|
|
|
|
else:
|
|
|
|
print(f"No server found with ID {server_id}")
|
|
|
|
|
|
|
|
def get_servers(self):
|
|
|
|
return self.servers.values()
|
2024-06-20 16:57:04 +00:00
|
|
|
|
2024-06-14 21:33:55 +00:00
|
|
|
def get_server_id_by_port(self, port):
|
|
|
|
for server_id, server_info in self.servers.items():
|
|
|
|
if server_info['port'] == port:
|
|
|
|
return server_id
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
pass
|