Last active 1736893123

Use this script to send rcon commands to a game server supporting Q3 Rcon

Revision 89b3017db0812b3e1cf6d46d04129e4c510aa271

rcon.py Raw
1#!/usr/bin/env python3
2
3# MIT License
4#
5# Copyright (c) 2025 Onyx and Iris
6#
7# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and associated documentation files (the "Software"), to deal
9# in the Software without restriction, including without limitation the rights
10# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11# copies of the Software, and to permit persons to whom the Software is
12# furnished to do so, subject to the following conditions:
13#
14# The above copyright notice and this permission notice shall be included in all
15# copies or substantial portions of the Software.
16#
17# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23# SOFTWARE.
24
25import argparse
26import re
27import socket
28
29
30class Packet:
31 MAGIC = bytearray([0xFF, 0xFF, 0xFF, 0xFF])
32
33
34class Request(Packet):
35 """
36 Class used to encode a request packet for remote console (RCON) communication.
37
38 Attributes:
39 password (str): The password used for authentication with the RCON server.
40
41 Methods:
42 _header() -> bytes:
43 Generates the header for the RCON packet.
44
45 encode(cmd: str) -> bytes:
46 Encodes the command into a byte string suitable for sending to the RCON server.
47 Args:
48 cmd (str): The command to be sent to the RCON server.
49 Returns:
50 bytes: The encoded command as a byte string.
51 """
52
53 def __init__(self, password: str):
54 self.password = password
55
56 def _header(self) -> bytes:
57 return Packet.MAGIC + b"rcon"
58
59 def encode(self, cmd: str) -> bytes:
60 return self._header() + f" {self.password} {cmd}".encode()
61
62
63class ResponseBuilder(Packet):
64 """
65 Class used to build and decode a response packet from multiple fragments.
66
67 Attributes:
68 _fragments (bytearray): A bytearray to store the concatenated fragments.
69
70 Methods:
71 _header() -> bytes:
72 Returns the header bytes that each fragment should start with.
73
74 is_valid_fragment(fragment: bytes) -> bool:
75 Checks if the given fragment starts with the expected header.
76
77 add_fragment(fragment: bytes):
78 Adds a fragment to the internal storage after removing the header.
79
80 build() -> str:
81 Decodes and returns the concatenated fragments as a string.
82 """
83
84 def __init__(self):
85 self._fragments = bytearray()
86
87 def _header(self) -> bytes:
88 return Packet.MAGIC + b"print\n"
89
90 def is_valid_fragment(self, fragment: bytes) -> bool:
91 return fragment.startswith(self._header())
92
93 def add_fragment(self, fragment: bytes):
94 self._fragments.extend(fragment.removeprefix(self._header()))
95
96 def build(self) -> str:
97 return self._fragments.decode()
98
99
100def send(sock: socket.socket, request: Request, host: str, port: int, cmd: str) -> str:
101 """
102 Send a single RCON (Remote Console) command to the server and return the response.
103
104 This function sends a command to a game server using the RCON protocol over a UDP socket.
105 It waits for the server's response, collects it in fragments if necessary, and returns the complete response.
106
107 Args:
108 sock (socket.socket): The UDP socket object used to send and receive data.
109 request (Request): An instance of the Request class used to encode the command.
110 host (str): The hostname or IP address of the server.
111 port (int): The port number on which the server is listening.
112 cmd (str): The RCON command to be sent to the server.
113
114 Returns:
115 str: The complete response from the server after processing all received fragments.
116
117 Raises:
118 socket.timeout: If the socket times out while waiting for a response from the server.
119 """
120 sock.sendto(request.encode(cmd), (host, port))
121
122 response_builder = ResponseBuilder()
123 while True:
124 try:
125 data, _ = sock.recvfrom(4096)
126 except socket.timeout:
127 break
128
129 if response_builder.is_valid_fragment(data):
130 response_builder.add_fragment(data)
131
132 return response_builder.build()
133
134
135def parse_args() -> argparse.Namespace:
136 parser = argparse.ArgumentParser()
137 parser.add_argument("--host", default="localhost")
138 parser.add_argument("--port", type=int, default=27960)
139 parser.add_argument("--password", default="secret")
140 parser.add_argument("--timeout", type=float, default=0.2)
141 parser.add_argument("--interactive", action="store_true")
142 parser.add_argument("cmd", nargs="?", default="status")
143 args = parser.parse_args()
144 return args
145
146
147def main():
148 """
149 Main function to handle command-line arguments and interact with a remote server using RCON protocol.
150 This function parses command-line arguments, creates a UDP socket, and sends requests to a remote server.
151 It supports both interactive and non-interactive modes.
152 In non-interactive mode, it sends a single command to the server and prints the response.
153 In interactive mode, it continuously prompts the user for commands until the user quits by entering 'Q'.
154 Args:
155 None
156 Returns:
157 None
158 """
159
160 def cleaned_response(resp: str) -> str:
161 return re.sub(r"\^[0-9]", "", resp)
162
163 args = parse_args()
164
165 with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
166 sock.settimeout(args.timeout)
167
168 request = Request(args.password)
169
170 if not args.interactive:
171 if resp := send(sock, request, args.host, args.port, args.cmd):
172 print(cleaned_response(resp))
173 return
174
175 while cmd := input("cmd: ").strip():
176 if cmd == "Q":
177 break
178
179 if resp := send(sock, request, args.host, args.port, cmd):
180 print(cleaned_response(resp))
181
182
183if __name__ == "__main__":
184 main()
185