Ubuntu Server部署的Minecraft服务器Python数据获取方案咨询
Absolutely! You can absolutely pull all that data from your Minecraft Server, and there are a few solid, straightforward ways to build your Python console app for this. Let’s break down the methods, focusing on the real-time player data and chat messages you care about most.
1. Use the RCON Protocol (Recommended for Structured Server Data)
Minecraft Server has built-in RCON support, which lets you send commands to the server and get structured responses—perfect for grabbing player counts, names, difficulty, seed, and even player positions.
Setup Steps:
First, enable RCON in your server.properties file (located in your Minecraft Server directory):
enable-rcon=true rcon.port=25575 rcon.password=your-secure-password-here
Restart your Minecraft Server after saving these changes.
Python Implementation:
Use the mcrcon library (a lightweight, pure-Python tool for RCON). Install it first via pip:
pip install mcrcon
Here’s a sample script to fetch core server status and player data:
from mcrcon import MCRcon import psutil # Configure your server details SERVER_HOST = "localhost" # Use your server's public IP if running the script remotely SERVER_RCON_PORT = 25575 SERVER_RCON_PASS = "your-secure-password-here" def get_server_status(): with MCRcon(SERVER_HOST, SERVER_RCON_PASS, port=SERVER_RCON_PORT) as mcr: # Get online players and count players_response = mcr.command("list") players_part = players_response.split(":")[-1].strip() online_players = players_part.split(", ") if players_part else [] player_count = len(online_players) # Get server difficulty difficulty = mcr.command("difficulty").strip() # Get world seed seed = mcr.command("seed").split(":")[-1].strip() # Get Java memory usage (since Minecraft runs on Java) mem_usage_mb = None for proc in psutil.process_iter(['name', 'cmdline']): try: if 'java' in proc.name() and 'minecraft_server' in ' '.join(proc.cmdline()): mem_info = proc.memory_info() mem_usage_mb = round(mem_info.rss / (1024 * 1024), 2) break except (psutil.NoSuchProcess, psutil.AccessDenied): continue return { "online_players": online_players, "player_count": player_count, "difficulty": difficulty, "seed": seed, "memory_usage_mb": mem_usage_mb } def get_player_position(player_name): with MCRcon(SERVER_HOST, SERVER_RCON_PASS, port=SERVER_RCON_PORT) as mcr: pos_response = mcr.command(f"data get entity {player_name} Pos") # Parse the response (format: "Pos: [x.0d, y.0d, z.0d]") pos_values = pos_response.split(":")[-1].strip().strip("[]").split(", ") x, y, z = [float(val.replace("d", "")) for val in pos_values] return {"x": x, "y": y, "z": z} # Example usage if __name__ == "__main__": status = get_server_status() print("=== Minecraft Server Status ===") print(f"Online Players ({status['player_count']}): {', '.join(status['online_players'])}") print(f"Difficulty: {status['difficulty']}") print(f"World Seed: {status['seed']}") print(f"Memory Usage: {status['memory_usage_mb']} MB" if status['memory_usage_mb'] else "Memory usage unavailable")
2. Parse Minecraft Server Logs (Best for Real-Time Chat & Events)
Minecraft logs all chat messages, player joins/leaves, and server events to logs/latest.log in your server directory. You can "tail" this file in Python to get instant updates.
Python Implementation for Log Tailing:
import time from pathlib import Path # Update this path to your Minecraft Server's log file SERVER_LOG_PATH = Path("/path/to/your/minecraft/server/logs/latest.log") def tail_logs(): # Open the log file and jump to the end to avoid reprocessing old lines with open(SERVER_LOG_PATH, "r") as log_file: log_file.seek(0, 2) while True: line = log_file.readline() if not line: time.sleep(0.1) continue # Parse chat messages if "<" in line and ">" in line: chat_parts = line.split("]: <") if len(chat_parts) >= 2: player = chat_parts[1].split(">")[0] message = chat_parts[1].split(">")[1].strip() print(f"[CHAT] {player}: {message}") # Parse player join events if "joined the game" in line: player = line.split("joined the game")[0].split("]: ")[1].strip() print(f"[EVENT] {player} has joined the server!") # Parse player leave events if "left the game" in line: player = line.split("left the game")[0].split("]: ")[1].strip() print(f"[EVENT] {player} has left the server!") # Example usage if __name__ == "__main__": tail_logs()
Notes:
- Ensure your Python script has read permissions for the log file (run
chmod +r logs/latest.logif needed). - Log formats might vary slightly for modded servers (Forge, Fabric, Paper), so tweak the parsing logic if necessary.
3. Combine Both Methods for a Full Console App
For a complete monitoring tool, run RCON status checks (on a timer) and log tailing in parallel using threads. Here’s a quick example:
import threading import time def status_updater(): while True: status = get_server_status() # Clear the console (Ubuntu uses 'clear'; use 'cls' for Windows) print("\033c", end="") print("=== Minecraft Server Monitor ===") print(f"Online Players ({status['player_count']}): {', '.join(status['online_players'])}") print(f"Difficulty: {status['difficulty']}") print(f"World Seed: {status['seed']}") print(f"Memory Usage: {status['memory_usage_mb']} MB" if status['memory_usage_mb'] else "Memory usage unavailable") print("\nRecent Chat/Events:") time.sleep(10) if __name__ == "__main__": # Start status updates in a background thread status_thread = threading.Thread(target=status_updater, daemon=True) status_thread.start() # Run log tailing in the main thread tail_logs()
Key Tips:
- Security: Never hardcode your RCON password in the script—use environment variables instead (e.g.,
os.getenv("MC_RCON_PASS")). - Compatibility: These methods work for Vanilla Minecraft Server and most modded servers that support RCON and standard logging.
- Real-Time Accuracy: RCON is great for periodic status checks, while log tailing gives you instant chat and join/leave events.
内容的提问来源于stack exchange,提问作者N3ttX




