You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

225 lines
9.8 KiB
Python

import os
import subprocess
import psutil
import keyboard # For capturing keyboard events
import signal
import time
from datetime import datetime
#logging.basicConfig(filename='osiris_listener_playground.log', level=logging.DEBUG, format='%(asctime)s %(message)s')
"""_
def read_pid_file(pid_file):
""Read the PID from the specified PID file.""
try:
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
return pid
except (FileNotFoundError, ValueError):
return None
def is_java_process_running(pid):
""Check if a Java process with the given PID is running.""
try:
proc = psutil.Process(pid)
if 'java' in proc.name().lower():
return True
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
return False
return False
SCRIPTS = {
"start_gameservers_minecraft": [
# Vanilla (Port 25565)
{"name": "Minecraft Vanilla 1.21", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/Vanilla_1-21/start_server.py", "params": ["--java_path", "C:/Program Files/Java/jdk-22/bin", "minecraft_server.1.21"]},
# The 1.12.2 Pack (SanderPack) (Port 25566)
{"name": "Minecraft The 1.12.2 Pack (SanderPack)", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/1-12-2-Pack/start_server.py", "params": ["--java_path", "C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin", 'forge-1.12.2-14.23.5.2860']},
# GT New Horizon (SanderHorizon) (Port 25567)
{"name": "Minecraft GT New Horizon 2.6.0 (SanderHorizon)", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/gt_new_horizons_2.6.0/start_server.py", "params": ["--java_path", "C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin'", 'forge-1.7.10-10.13.4.1614-1.7.10-universal']},
# rlcraft (SanderHardcore) (Port 25568)
{"name": "Minecraft rlcraft 2.9.3 (SanderHardcore)", "path": "C:/Users/4lexK/Desktop/GameServers/Minecraft/rlcraft/start_server.py", "params": ["--java_path", "C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin'", 'forge-1.12.2-14.23.5.2860']},
# Add more scripts and their parameters as needed
]
}
logging.info("Received request to start minecraft servers.")
6 months ago
current_pid = []
results = []
for script_info in SCRIPTS['start_gameservers_minecraft']:
path = script_info["path"]
params = script_info["params"]
script_name = script_info["name"]
pid_file = os.path.join(os.path.dirname(path), 'server.pid')
pid = read_pid_file(pid_file)
if pid and is_java_process_running(pid):
logging.info(f"Script {script_name} is already running with PID {pid}.")
results.append({
"script": path,
"params": params,
"status": "already running",
"pid": pid
})
continue
try:
logging.info(f"Starting script: {' '.join(['python', path] + params)}")
process = subprocess.Popen(['python', path] + params, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
psutil_process = psutil.Process(process.pid)
logging.info(f"Started {script_name} with PID: {psutil_process.pid}")
results.append({
"script": path,
"params": params,
"pid": psutil_process.pid
})
except Exception as e:
logging.error(f"Error starting script {path}: {e}")
results.append({
"script": path,
"params": params,
"error": str(e)
})
logging.info(f"{results =}")
# ""
current_pid = 8196
try:
subprocess.run(['taskkill', '/F', '/PID', str(current_pid)], check=True)
print(f"Process with PID {current_pid} has been terminated.")
except subprocess.CalledProcessError as e:
print(f"Failed to terminate process with PID {current_pid}. Error: {e}")
#""
"""
# Define your list of Java server directories and commands
java_servers = [
{
'server_name': 'Vanilla 1.21',
'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/Vanilla_1-21/',
'command': ['C:/Program Files/Java/jdk-22/bin/java.exe', '-Xmx1024M', '-Xms1024M', '-jar', 'minecraft_server.1.21.jar', '--nogui', '--bonusChest'],
'wait_time': 30
},
{
5 months ago
'server_name': 'The 1.12.2 Pack (SanderPack)',
'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/1-12-2-Pack/',
'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx16G', '-XX:+UseG1GC','-Xms4G', '-Dsun.rmi.dgc.server.gcInterval=2147483646', '-XX:+UnlockExperimentalVMOptions', '-XX:G1NewSizePercent=20', '-XX:G1ReservePercent=20', '-XX:MaxGCPauseMillis=50', '-XX:G1HeapRegionSize=32M', '-Dfml.queryResult=confirm', '-Duser.language=en', '-jar', 'forge-1.12.2-14.23.5.2860.jar', '--nogui', '--bonusChest'],
'wait_time': 300
},
{
'server_name': 'GT New Horizons 2.6.0 (SanderHorizons)',
'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/gt_new_horizons_2.6.0/',
'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx12G', '-Xms4G', '-XX:+UseStringDeduplication', '-XX:+UseCompressedOops', '-XX:+UseCodeCacheFlushing', '-Dfml.readTimeout=180', '-jar', 'forge-1.7.10-10.13.4.1614-1.7.10-universal.jar', '--nogui', '--bonusChest'],
'wait_time': 300
5 months ago
},
{
'server_name': 'RLCraft 2.9.3 (SanderHardcore)',
'directory': 'C:/Users/4lexK/Desktop/GameServers/Minecraft/rlcraft/',
'command': ['C:/Program Files/OpenLogic/jdk-8.0.412.08-hotspot/bin/java.exe', '-Xmx16G', '-Xms4G', '-jar', 'forge-1.12.2-14.23.5.2860.jar', '--nogui', '--bonusChest'],
'wait_time': 300
}
]
def is_java_process(pid):
try:
p = psutil.Process(pid)
return 'java' in p.name().lower()
except psutil.NoSuchProcess:
return False
def start_servers():
for server in java_servers:
os.chdir(server['directory'])
pid_file = os.path.join(server['directory'], 'server.pid')
log_file = os.path.join(server['directory'], 'logs', f'server_{datetime.now().strftime("%Y%m%d_%H%M%S")}.log')
wait_time = server['wait_time']
# Create logs directory if it doesn't exist
os.makedirs(os.path.dirname(log_file), exist_ok=True)
if os.path.exists(pid_file):
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
if psutil.pid_exists(pid) and is_java_process(pid):
print(f"Server in {server['directory']} is already running.")
continue
else:
os.remove(pid_file)
print(f"Starting server in {server['directory']}")
with open(log_file, 'w') as log:
process = subprocess.Popen(
server['command'],
cwd=server['directory'],
stdout=log,
stderr=log,
creationflags=subprocess.CREATE_NEW_PROCESS_GROUP if os.name == 'nt' else 0
)
5 months ago
#time.sleep(wait_time)
with open(pid_file, 'w') as file:
file.write(str(process.pid))
print(f"Server in {server['directory']} with PID {process.pid} started successfully.")
def check_status():
for server in java_servers:
pid_file = os.path.join(server['directory'], 'server.pid')
if os.path.exists(pid_file):
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
if psutil.pid_exists(pid) and is_java_process(pid):
print(f"Server in {server['directory']} is running with PID {pid}.")
else:
print(f"Server in {server['directory']} is not running.")
else:
print(f"No PID file found for server in {server['directory']}.")
def stop_servers():
for server in java_servers:
pid_file = os.path.join(server['directory'], 'server.pid')
wait_time = server['wait_time']
flag_delete_pid = False
if os.path.exists(pid_file):
with open(pid_file, 'r') as file:
pid = int(file.read().strip())
if psutil.pid_exists(pid) and is_java_process(pid):
p = psutil.Process(pid)
if os.name == 'nt':
p.terminate() # Use terminate for Windows
else:
p.send_signal(signal.SIGTERM)
try:
p.wait(timeout=wait_time)
if not psutil.pid_exists(pid):
flag_delete_pid = True
print(f"Stopped server in {server['directory']} with PID {pid}.")
else:
print(f"Failed to stop server in {server['directory']} with PID {pid}.")
except psutil.TimeoutExpired:
print(f"Timeout while stopping server in {server['directory']} with PID {pid}.")
else:
flag_delete_pid = True
print(f"Removed stale PID file for server in {server['directory']}.")
if flag_delete_pid:
os.remove(pid_file)
print(f"PID File Deleted")
flag_delete_pid = False
else:
print(f"No PID File for Server {server['server_name']}")
def main():
print("Press 'S' to start servers, 'D' to check status, 'F' to stop servers, and 'X' to exit.")
while True:
if keyboard.is_pressed('x'):
print("Exiting program.")
break
elif keyboard.is_pressed('s'):
start_servers()
elif keyboard.is_pressed('d'):
check_status()
elif keyboard.is_pressed('f'):
stop_servers()
time.sleep(0.1) # Small sleep to prevent high CPU usages
if __name__ == "__main__":
main()