### MCRcon Command-Line Interface (CLI) Usage Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Provides examples of using the mcrcon command-line tool for interactive and automated Minecraft server administration. Covers installation, interactive sessions with password prompts, environment variable usage for credentials, custom ports, TLS connections, and executing single commands via pipes. Requires the 'mcrcon' package. ```bash # Install the package pip install mcrcon # Interactive mode with password prompt mcrcon minecraft.example.com # Password: [enters password securely] # > /list # > /whitelist add newplayer # > exit # Using environment variable for password export RCON_PASSWORD=my_secret_password mcrcon 10.1.1.1 # > /time set day # > /weather clear # > /give @a minecraft:diamond 1 # > stop # With password argument (less secure, visible in process list) mcrcon --password supersecret minecraft.local --port 25575 # Custom port mcrcon minecraft.local -p 25580 # With TLS encryption mcrcon --tls secure-server.example.com -p 25575 # Quick command execution (non-interactive) echo "/list" | mcrcon minecraft.local # Environment setup for automation export RCON_PASSWORD=automation_pass export MC_SERVER=10.1.1.1 echo "/save-all" | mcrcon $MC_SERVER echo "/say Server backup starting" | mcrcon $MC_SERVER ``` -------------------------------- ### Initialize MCRcon Client with Various Settings (Python) Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Demonstrates initializing the MCRcon client with different configurations, including basic setup with default ports, full parameter specification, and TLS-enabled connections. The `tlsmode` parameter controls TLS behavior, and `timeout` sets connection duration. ```python from mcrcon import MCRcon # Basic initialization with default port (25575) mcr = MCRcon("minecraft.example.com", "my_secret_password") # Full initialization with custom settings mcr = MCRcon( host="10.1.1.100", password="super_secure_pass", port=25575, tlsmode=0, # 0=no TLS, 1=TLS with verification, 2=TLS without verification timeout=5 # seconds ) # With TLS encryption enabled mcr_tls = MCRcon( host="secure-minecraft.example.com", password="encrypted_pass", port=25575, tlsmode=1, timeout=10 ) ``` -------------------------------- ### MCRcon Command Line Interface (CLI) Usage Source: https://github.com/uncaught-exceptions/mcrcon/blob/master/README.rst Shows how to use the MCRcon command-line interface after installation. The CLI allows for direct RCON command execution from the terminal. It includes examples for getting help, connecting to a server, and setting the RCON password via an environment variable for interactive command input. ```bash mcrcon --help ``` ```bash mcrcon 10.1.1.1 ``` ```bash export RCON_PASSWORD=sekret > /whitelist add bob ``` -------------------------------- ### Context Manager Usage (Recommended) Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Utilize MCRcon with Python's context manager for automatic connection setup and teardown, ensuring proper socket cleanup even if exceptions occur. ```APIDOC ## Context Manager Usage (Recommended) ### Description Using MCRcon with Python's context manager automatically handles connection setup and teardown, ensuring proper socket cleanup even if exceptions occur during command execution. ### Method `with MCRcon(host, password, ...)` ### Endpoint N/A (Context Manager) ### Parameters See `MCRcon` Class Initialization for parameters. ### Request Example ```python from mcrcon import MCRcon # Context manager ensures proper connection cleanup with MCRcon("10.1.1.1", "sekret") as mcr: # Add player to whitelist response = mcr.command("/whitelist add bob") print(f"Whitelist response: {response}") # Get server time time_response = mcr.command("/time query daytime") print(f"Server time: {time_response}") # List online players players = mcr.command("/list") print(f"Online players: {players}") # Set game mode gamemode = mcr.command("/gamemode creative alice") print(f"Gamemode change: {gamemode}") # Socket is automatically closed here, even if an error occurred ``` ### Response #### Success Response (200) Depends on the command executed. Returns the server's response string. #### Response Example ``` Whitelist response: Added bob to the whitelist! Server time: 3000 Online players: There are 5 of a max of 20 players online: Player1, Player2, Player3, Player4, Player5 Gamemode change: Changed alice's game mode to creative. ``` ``` -------------------------------- ### Execute Minecraft Commands using MCRcon Context Manager (Python) Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Shows how to use MCRcon within a Python context manager (`with` statement) for automatic connection handling. This ensures the RCON connection is properly closed even if errors occur. Example commands include whitelisting, querying time, listing players, and changing game modes. ```python from mcrcon import MCRcon # Context manager ensures proper connection cleanup with MCRcon("10.1.1.1", "sekret") as mcr: # Add player to whitelist response = mcr.command("/whitelist add bob") print(f"Whitelist response: {response}") # Get server time time_response = mcr.command("/time query daytime") print(f"Server time: {time_response}") # List online players players = mcr.command("/list") print(f"Online players: {players}") # Set game mode gamemode = mcr.command("/gamemode creative alice") print(f"Gamemode change: {gamemode}") # Socket is automatically closed here, even if an error occurred ``` -------------------------------- ### Monitor Minecraft Server Player Count and Status with MCRcon Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt This Python class, `MinecraftServerMonitor`, leverages MCRcon to interact with a Minecraft server. It provides methods to retrieve the current player count by parsing the '/list' command output and to get server TPS using a '/forge tps' command. The class includes error handling for network issues and command execution failures. It's designed for integration into server monitoring systems. ```python from mcrcon import MCRcon import re import time class MinecraftServerMonitor: def __init__(self, host, password, port=25575): self.host = host self.password = password self.port = port def get_player_count(self): """Extract current player count from server""" try: with MCRcon(self.host, self.password, self.port) as mcr: response = mcr.command("/list") # Parse response like "There are 5 of a max of 20 players online" match = re.search(r'There are (\d+)', response) if match: return int(match.group(1)) except Exception as e: print(f"Error getting player count: {e}") return None def get_tps(self): """Get server TPS (if forge/spigot command available)""" try: with MCRcon(self.host, self.password, self.port) as mcr: response = mcr.command("/forge tps") return response except Exception: return None def restart_if_empty(self): """Restart server if no players online""" count = self.get_player_count() if count == 0: try: with MCRcon(self.host, self.password, self.port) as mcr: mcr.command("/say Server restart in 30 seconds") time.sleep(30) mcr.command("/stop") return True except Exception as e: print(f"Restart failed: {e}") return False # Usage monitor = MinecraftServerMonitor("10.1.1.1", "monitor_pass") players = monitor.get_player_count() print(f"Current players online: {players}") if players == 0: print("Server empty, scheduling maintenance") monitor.restart_if_empty() ``` -------------------------------- ### MCRcon Class Initialization Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Initialize an MCRcon client instance with connection parameters including host, password, port, TLS mode, and timeout. Supports default and full initialization with custom settings. ```APIDOC ## MCRcon Class Initialization ### Description The MCRcon class constructor creates a new RCON client instance with connection parameters. It accepts host, password, port, TLS mode, and timeout settings, preparing the client for connection to a Minecraft server. ### Method `MCRcon(host, password, port=25575, tlsmode=0, timeout=5)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from mcrcon import MCRcon # Basic initialization with default port (25575) mcr = MCRcon("minecraft.example.com", "my_secret_password") # Full initialization with custom settings mcr = MCRcon( host="10.1.1.100", password="super_secure_pass", port=25575, tlsmode=0, # 0=no TLS, 1=TLS with verification, 2=TLS without verification timeout=5 # seconds ) # With TLS encryption enabled mcr_tls = MCRcon( host="secure-minecraft.example.com", password="encrypted_pass", port=25575, tlsmode=1, timeout=10 ) ``` ### Response None (This is a constructor) #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Manual MCRcon Connection and Command Execution with Error Handling (Python) Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Illustrates manual connection management using `connect()` and `disconnect()` methods of the MCRcon client. This approach provides explicit control over the connection lifecycle and includes robust error handling for `MCRconException`, `ConnectionRefusedError`, and general exceptions. ```python from mcrcon import MCRcon, MCRconException mcr = MCRcon("10.1.1.1", "sekret", port=25575) try: # Explicitly connect to server mcr.connect() # Execute multiple commands resp1 = mcr.command("/whitelist add bob") print(f"Response 1: {resp1}") resp2 = mcr.command("/give bob minecraft:diamond 64") print(f"Response 2: {resp2}") resp3 = mcr.command("/tp bob 100 64 200") print(f"Response 3: {resp3}") except MCRconException as e: print(f"RCON error occurred: {e}") except ConnectionRefusedError: print("Server refused connection - check if RCON is enabled") except Exception as e: print(f"Unexpected error: {e}") finally: # Always disconnect to clean up resources mcr.disconnect() ``` -------------------------------- ### Send Various Minecraft Server Commands using MCRcon (Python) Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Demonstrates sending diverse Minecraft server commands via the MCRcon client's `command()` method within a context manager. This includes server status, player management (kick), world settings (weather, difficulty), and custom plugin commands. ```python from mcrcon import MCRcon with MCRcon("minecraft.server.local", "admin_password") as mcr: # Server management commands status = mcr.command("/list") print(f"Server status: {status}") # Player management kick_response = mcr.command("/kick griefer123 Griefing not allowed") print(f"Kick result: {kick_response}") # World management weather = mcr.command("/weather clear") print(f"Weather changed: {weather}") # Configuration commands difficulty = mcr.command("/difficulty hard") print(f"Difficulty set: {difficulty}") # Custom plugin commands (if server has plugins) custom = mcr.command("/myplugin reload") print(f"Plugin response: {custom}") # Server control save = mcr.command("/save-all") print(f"Save result: {save}") ``` -------------------------------- ### Python MCRcon Client Manual Connection Usage Source: https://github.com/uncaught-exceptions/mcrcon/blob/master/README.rst Illustrates how to use the MCRcon client manually without the 'with' statement. This requires explicit calls to connect() and disconnect() to manage the RCON socket. It shows initializing the client, connecting, executing a command, printing the response, and finally disconnecting. ```python from mcrcon import MCRcon mcr = MCRcon("10.1.1.1", "sekret") mcr.connect() resp = mcr.command("/whitelist add bob") print(resp) mcr.disconnect() ``` -------------------------------- ### Execute Daily Maintenance Commands with MCRcon Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt This Python snippet demonstrates how to execute a list of predefined maintenance commands on a Minecraft server using MCRcon. It includes saving the game, managing server messages, and setting the weather and time. The function `execute_batch_commands` is assumed to be defined elsewhere and handles the actual communication with the RCON server. ```python maintenance_commands = [ "/save-all", "/save-off", "/say Backup starting in 10 seconds", "/weather clear", "/time set day", "/save-on", "/say Backup complete" ] results = execute_batch_commands("10.1.1.1", "admin_pass", maintenance_commands) if results: successful = sum(1 for r in results if r["success"]) print(f"Completed {successful}/{len(results)} commands successfully") ``` -------------------------------- ### Secure Minecraft RCON Connections with TLS/SSL in Python Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Demonstrates how to establish secure RCON connections using TLS encryption with varying levels of certificate verification. Supports full verification, skipping verification for self-signed certificates, and no encryption. Requires the 'mcrcon' library. ```python from mcrcon import MCRcon # TLS with full certificate verification (most secure) with MCRcon( host="secure.minecraft.net", password="encrypted_pass", port=25575, tlsmode=1 # Enable TLS with hostname and certificate verification ) as mcr: response = mcr.command("/list") print(f"Secure response: {response}") # TLS without certificate verification (self-signed certificates) with MCRcon( host="192.168.1.100", password="local_pass", port=25575, tlsmode=2 # Enable TLS but skip certificate validation ) as mcr: response = mcr.command("/whitelist add player1") print(f"Response: {response}") # No encryption (default, fastest but insecure over internet) with MCRcon( host="localhost", password="local_only", port=25575, tlsmode=0 # No TLS encryption ) as mcr: response = mcr.command("/save-all") print(f"Response: {response}") ``` -------------------------------- ### Execute Batch RCON Commands with Logging in Python Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt A Python function to execute multiple RCON commands sequentially, with detailed logging for each command's execution status and response. It handles potential connection errors and individual command failures, returning a list of results or None if the connection fails. Requires 'mcrcon' and 'logging' modules. ```python from mcrcon import MCRcon, MCRconException import logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) def execute_batch_commands(host, password, commands): """Execute a batch of RCON commands with logging""" results = [] try: with MCRcon(host, password, timeout=15) as mcr: for cmd in commands: try: logger.info(f"Executing: {cmd}") response = mcr.command(cmd) results.append({ "command": cmd, "success": True, "response": response }) logger.info(f"Success: {response}") except Exception as e: results.append({ "command": cmd, "success": False, "error": str(e) }) logger.error(f"Failed: {e}") except MCRconException as e: logger.error(f"Connection failed: {e}") return None return results ``` -------------------------------- ### Manual Connection Management Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt For explicit connection control, MCRcon supports manual connect and disconnect operations, providing fine-grained control over the connection lifecycle. ```APIDOC ## Manual Connection Management ### Description For scenarios requiring explicit connection control, MCRcon supports manual connect and disconnect operations, giving developers fine-grained control over the connection lifecycle. ### Method `connect()` and `disconnect()` ### Endpoint N/A (Manual Connection) ### Parameters - `connect()`: No parameters. - `disconnect()`: No parameters. ### Request Example ```python from mcrcon import MCRcon, MCRconException mcr = MCRcon("10.1.1.1", "sekret", port=25575) try: # Explicitly connect to server mcr.connect() # Execute multiple commands resp1 = mcr.command("/whitelist add bob") print(f"Response 1: {resp1}") resp2 = mcr.command("/give bob minecraft:diamond 64") print(f"Response 2: {resp2}") resp3 = mcr.command("/tp bob 100 64 200") print(f"Response 3: {resp3}") except MCRconException as e: print(f"RCON error occurred: {e}") except ConnectionRefusedError: print("Server refused connection - check if RCON is enabled") except Exception as e: print(f"Unexpected error: {e}") finally: # Always disconnect to clean up resources mcr.disconnect() ``` ### Response #### Success Response (200) Depends on the command executed. Returns the server's response string. #### Response Example ``` Response 1: Added bob to the whitelist! Response 2: Granted 64 diamond to bob Response 3: Teleported bob to 100, 64, 200 ``` ``` -------------------------------- ### Command Execution Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt The `command` method sends arbitrary Minecraft server commands and returns the server's response. It handles RCON protocol packet encoding, transmission, and response parsing automatically. ```APIDOC ## Command Execution ### Description The command method sends arbitrary Minecraft server commands and returns the server's response. It handles the RCON protocol packet encoding, transmission, and response parsing automatically. ### Method `command(command_string)` ### Endpoint N/A (Method within MCRcon instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python from mcrcon import MCRcon with MCRcon("minecraft.server.local", "admin_password") as mcr: # Server management commands status = mcr.command("/list") print(f"Server status: {status}") # Player management kick_response = mcr.command("/kick griefer123 Griefing not allowed") print(f"Kick result: {kick_response}") # World management weather = mcr.command("/weather clear") print(f"Weather changed: {weather}") # Configuration commands difficulty = mcr.command("/difficulty hard") print(f"Difficulty set: {difficulty}") # Custom plugin commands (if server has plugins) custom = mcr.command("/myplugin reload") print(f"Plugin response: {custom}") # Server control save = mcr.command("/save-all") print(f"Save result: {save}") ``` ### Response #### Success Response (200) The server's textual response to the executed command. #### Response Example ``` Server status: There are 3 of a max of 20 players online: PlayerA, PlayerB, PlayerC Kick result: kicked griefer123: Griefing not allowed Weather changed: Set weather to clear. Difficulty set: Set difficulty to hard. Plugin response: Plugin reloaded successfully. Save result: Saved the game. ``` ``` -------------------------------- ### Python MCRcon Client Usage with 'with' statement Source: https://github.com/uncaught-exceptions/mcrcon/blob/master/README.rst Demonstrates the recommended way to use the MCRcon client in Python, utilizing the 'with' statement for automatic socket management. This ensures the RCON connection is properly closed after use. It takes the server IP and password as arguments and executes a command, printing the response. ```python from mcrcon import MCRcon with MCRcon("10.1.1.1", "sekret") as mcr: resp = mcr.command("/whitelist add bob") print(resp) ``` -------------------------------- ### Execute RCON Commands Safely in Python Source: https://context7.com/uncaught-exceptions/mcrcon/llms.txt Executes RCON commands with comprehensive error handling for authentication failures, connection issues, protocol violations, and timeouts. It returns a dictionary indicating success or failure with specific error messages. Dependencies include the 'mcrcon' library and Python's 'socket' module. ```python from mcrcon import MCRcon, MCRconException import socket def safe_rcon_command(host, password, command): """Execute RCON command with comprehensive error handling""" try: with MCRcon(host, password, timeout=10) as mcr: response = mcr.command(command) return {"success": True, "response": response} except MCRconException as e: # Authentication failure or protocol error if "Login failed" in str(e): return {"success": False, "error": "Invalid RCON password"} elif "timeout" in str(e).lower(): return {"success": False, "error": "Connection timeout"} else: return {"success": False, "error": f"RCON error: {e}"} except ConnectionRefusedError: return {"success": False, "error": "Server refused connection - RCON may be disabled"} except socket.gaierror: return {"success": False, "error": "Invalid hostname or DNS resolution failed"} except Exception as e: return {"success": False, "error": f"Unexpected error: {e}"} # Usage example result = safe_rcon_command("10.1.1.1", "wrong_password", "/list") if result["success"]: print(f"Command output: {result['response']}") else: print(f"Error: {result['error']}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.