Skip to content

Instantly share code, notes, and snippets.

@onyx-and-iris
Last active February 26, 2026 18:00
Show Gist options
  • Select an option

  • Save onyx-and-iris/dfbc88b12dd0976a4f070251d561828d to your computer and use it in GitHub Desktop.

Select an option

Save onyx-and-iris/dfbc88b12dd0976a4f070251d561828d to your computer and use it in GitHub Desktop.
Q3 Rcon CLI - single file, zero dependencies
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2025 Onyx and Iris
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""
q3rcon.py
This script provides functionality to interact with a remote server using the RCON (Remote Console) protocol.
It includes classes to encode and decode RCON packets, send commands to the server, and handle responses.
The script also provides a command-line interface for sending RCON commands to a server.
Classes:
Packet: Base class for RCON packets.
Request: Class to encode a request packet for RCON communication.
ResponseFragment: Class to build and decode a response packet from multiple fragments received from the RCON server.
Functions:
send(sock: socket.socket, request: Request, host: str, port: int, cmd: str) -> str:
Sends an RCON command to the server and returns the response.
parse_args() -> argparse.Namespace:
Parses command-line arguments.
main():
Main function to handle command-line arguments and interact with a remote server using RCON protocol.
Usage:
To send a single command to the server:
python q3rcon.py --host <server_host> --port <server_port> --password <rcon_password> <command>
To specify multiple commands:
python q3rcon.py --host <server_host> --port <server_port> --password <rcon_password> <command1> <command2> ...
To use interactive mode:
python q3rcon.py --host <server_host> --port <server_port> --password <rcon_password> -i
"""
import argparse
import logging
import re
import socket
logger = logging.getLogger(__name__)
class Packet:
MAGIC = b'\xff\xff\xff\xff'
class Request(Packet):
"""
Class used to encode a request packet for remote console (RCON) communication.
Attributes:
password (str): The password used for authentication with the RCON server.
Methods:
_header() -> bytes:
Returns the header bytes that should be prefixed to the request packet.
from_credentials(password: str) -> Request:
Class method to create a Request instance from the given password.
to_bytes(cmd: str) -> bytes:
Converts the request to bytes format, including the command to be sent to the server.
"""
def __init__(self, password: str):
self.password = password
def _header(self) -> bytes:
return Packet.MAGIC + b'rcon'
@classmethod
def from_credentials(cls, password: str) -> 'Request':
return cls(password)
def to_bytes(self, cmd: str) -> bytes:
return self._header() + f' {self.password} {cmd}\n'.encode()
class ResponseFragment(Packet):
"""
Class used to build and decode a response packet from multiple fragments received from the RCON server.
Methods:
_header() -> bytes:
Returns the header bytes that should be prefixed to the response fragment.
from_bytes(data: bytes) -> str:
Class method to create a ResponseFragment instance from the given bytes data.
It checks if the data starts with the expected header and extracts the response content.
If the data does not start with the expected header, it raises a ValueError.
"""
def _header(self) -> bytes:
return self.MAGIC + b'print\n'
@classmethod
def from_bytes(cls, data: bytes) -> str:
instance = cls()
if not data.startswith(instance._header()):
raise ValueError('Invalid fragment: does not start with expected header')
return data.removeprefix(instance._header()).decode()
def send(sock: socket.socket, args: argparse.Namespace, cmd: str) -> str:
"""
Send a single RCON (Remote Console) command to the server and return the response.
This function sends a command to a game server using the RCON protocol over a UDP socket.
It waits for the server's response, collects it in fragments if necessary, and returns the complete response.
Args:
sock (socket.socket): The UDP socket used for communication with the server.
args (argparse.Namespace): The command-line arguments containing host, port, and password.
cmd (str): The command to be sent to the server.
Returns:
str: The complete response from the server after sending the command.
Raises:
ValueError: If any of the response fragments received from the server are invalid.
"""
raw_packet = Request.from_credentials(args.password).to_bytes(cmd)
logger.debug('Sending packet: %s', raw_packet)
sock.sendto(raw_packet, (args.host, args.port))
fragments = []
try:
while resp := sock.recv(2048):
try:
fragment = ResponseFragment.from_bytes(resp)
except ValueError:
logger.debug('Received invalid fragment, skipping: %s', resp)
continue
fragments.append(fragment)
except socket.timeout:
logger.debug('Finished receiving fragments (socket timeout)')
return ''.join(fragments)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument('--host', '-H', default='localhost')
parser.add_argument('--port', '-P', type=int, default=27960)
parser.add_argument('--password', '-p', default='')
parser.add_argument('--timeout', '-t', type=float, default=0.2)
parser.add_argument('--interactive', '-i', action='store_true')
parser.add_argument(
'--loglevel',
'-l',
default='info',
choices=['debug', 'info', 'warning', 'error', 'critical'],
help='Set the logging level (default: info)',
)
parser.add_argument('cmds', nargs='+', default=['status'])
args = parser.parse_args()
return args
def main(args: argparse.Namespace):
"""
Main function to handle command-line arguments and interact with a remote server using RCON protocol.
This function parses command-line arguments, creates a UDP socket, and sends requests to a remote server.
It supports both interactive and non-interactive modes.
Args:
args (argparse.Namespace): The command-line arguments containing
host, port, password, timeout, interactive mode flag, log level, and commands to be sent.
Behavior:
- If interactive mode is enabled, it prompts the user for commands until 'Q' is entered.
- If interactive mode is not enabled, it sends each command from the list of commands provided in the command-line arguments and prints the responses.
"""
def cleaned_response(resp: str) -> str:
return re.sub(r'\^[0-9]', '', resp)
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(args.timeout)
if args.interactive:
print("Entering interactive mode. Type 'Q' to quit.")
while cmd := input('cmd: ').strip():
if cmd == 'Q':
break
if resp := send(sock, args, cmd):
print(cleaned_response(resp))
else:
for cmd in args.cmds:
if resp := send(sock, args, cmd):
print(cleaned_response(resp))
if __name__ == '__main__':
args = parse_args()
logging.basicConfig(level=getattr(logging, args.loglevel.upper()))
main(args)
@onyx-and-iris
Copy link
Author

onyx-and-iris commented Jan 11, 2025

chmod +x this script and run it directly like so:

Example usage:

./rcon.py --host=localhost --port=28960 --password="$RCON_PASSWORD" -i

Then place it somewhere like /usr/bin/local if you want it to be discoverable.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment