rcon.py
· 7.3 KiB · Python
原始檔案
#!/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.
"""
rcon.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.
ResponseBuilder: Class to build and decode a response packet from multiple fragments.
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 rcon.py --host <server_host> --port <server_port> --password <rcon_password> <command>
To use interactive mode:
python rcon.py --host <server_host> --port <server_port> --password <rcon_password> --interactive
"""
import argparse
import re
import socket
class Packet:
MAGIC = bytearray([0xFF, 0xFF, 0xFF, 0xFF])
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:
Generates the header for the RCON packet.
encode(cmd: str) -> bytes:
Encodes the command into a byte string suitable for sending to the RCON server.
Args:
cmd (str): The command to be sent to the RCON server.
Returns:
bytes: The encoded command as a byte string.
"""
def __init__(self, password: str):
self.password = password
def _header(self) -> bytes:
return Packet.MAGIC + b"rcon"
def encode(self, cmd: str) -> bytes:
return self._header() + f" {self.password} {cmd}".encode()
class ResponseBuilder(Packet):
"""
Class used to build and decode a response packet from multiple fragments.
Attributes:
_fragments (bytearray): A bytearray to store the concatenated fragments.
Methods:
_header() -> bytes:
Returns the header bytes that each fragment should start with.
is_valid_fragment(fragment: bytes) -> bool:
Checks if the given fragment starts with the expected header.
add_fragment(fragment: bytes):
Adds a fragment to the internal storage after removing the header.
build() -> str:
Decodes and returns the concatenated fragments as a string.
"""
def __init__(self):
self._fragments = bytearray()
def _header(self) -> bytes:
return Packet.MAGIC + b"print\n"
def is_valid_fragment(self, fragment: bytes) -> bool:
return fragment.startswith(self._header())
def add_fragment(self, fragment: bytes):
self._fragments.extend(fragment.removeprefix(self._header()))
def build(self) -> str:
return self._fragments.decode()
def send(sock: socket.socket, request: Request, host: str, port: int, 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 object used to send and receive data.
request (Request): An instance of the Request class used to encode the command.
host (str): The hostname or IP address of the server.
port (int): The port number on which the server is listening.
cmd (str): The RCON command to be sent to the server.
Returns:
str: The complete response from the server after processing all received fragments.
Raises:
socket.timeout: If the socket times out while waiting for a response from the server.
"""
sock.sendto(request.encode(cmd), (host, port))
response_builder = ResponseBuilder()
while True:
try:
data, _ = sock.recvfrom(4096)
except socket.timeout:
break
if response_builder.is_valid_fragment(data):
response_builder.add_fragment(data)
return response_builder.build()
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--host", default="localhost")
parser.add_argument("--port", type=int, default=27960)
parser.add_argument("--password", default="secret")
parser.add_argument("--timeout", type=float, default=0.2)
parser.add_argument("--interactive", action="store_true")
parser.add_argument("cmd", nargs="?", default="status")
args = parser.parse_args()
return args
def main():
"""
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.
In non-interactive mode, it sends a single command to the server and prints the response.
In interactive mode, it continuously prompts the user for commands until the user quits by entering 'Q'.
Args:
None
Returns:
None
"""
def cleaned_response(resp: str) -> str:
return re.sub(r"\^[0-9]", "", resp)
args = parse_args()
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock:
sock.settimeout(args.timeout)
request = Request(args.password)
if not args.interactive:
if resp := send(sock, request, args.host, args.port, args.cmd):
print(cleaned_response(resp))
return
while cmd := input("cmd: ").strip():
if cmd == "Q":
break
if resp := send(sock, request, args.host, args.port, cmd):
print(cleaned_response(resp))
if __name__ == "__main__":
main()
| 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 | |
| 25 | """ |
| 26 | rcon.py |
| 27 | |
| 28 | This script provides functionality to interact with a remote server using the RCON (Remote Console) protocol. |
| 29 | |
| 30 | It includes classes to encode and decode RCON packets, send commands to the server, and handle responses. |
| 31 | The script also provides a command-line interface for sending RCON commands to a server. |
| 32 | |
| 33 | Classes: |
| 34 | Packet: Base class for RCON packets. |
| 35 | Request: Class to encode a request packet for RCON communication. |
| 36 | ResponseBuilder: Class to build and decode a response packet from multiple fragments. |
| 37 | |
| 38 | Functions: |
| 39 | send(sock: socket.socket, request: Request, host: str, port: int, cmd: str) -> str: |
| 40 | Sends an RCON command to the server and returns the response. |
| 41 | parse_args() -> argparse.Namespace: |
| 42 | Parses command-line arguments. |
| 43 | main(): |
| 44 | Main function to handle command-line arguments and interact with a remote server using RCON protocol. |
| 45 | |
| 46 | Usage: |
| 47 | To send a single command to the server: |
| 48 | python rcon.py --host <server_host> --port <server_port> --password <rcon_password> <command> |
| 49 | |
| 50 | To use interactive mode: |
| 51 | python rcon.py --host <server_host> --port <server_port> --password <rcon_password> --interactive |
| 52 | """ |
| 53 | |
| 54 | import argparse |
| 55 | import re |
| 56 | import socket |
| 57 | |
| 58 | |
| 59 | class Packet: |
| 60 | MAGIC = bytearray([0xFF, 0xFF, 0xFF, 0xFF]) |
| 61 | |
| 62 | |
| 63 | class Request(Packet): |
| 64 | """ |
| 65 | Class used to encode a request packet for remote console (RCON) communication. |
| 66 | |
| 67 | Attributes: |
| 68 | password (str): The password used for authentication with the RCON server. |
| 69 | |
| 70 | Methods: |
| 71 | _header() -> bytes: |
| 72 | Generates the header for the RCON packet. |
| 73 | |
| 74 | encode(cmd: str) -> bytes: |
| 75 | Encodes the command into a byte string suitable for sending to the RCON server. |
| 76 | Args: |
| 77 | cmd (str): The command to be sent to the RCON server. |
| 78 | Returns: |
| 79 | bytes: The encoded command as a byte string. |
| 80 | """ |
| 81 | |
| 82 | def __init__(self, password: str): |
| 83 | self.password = password |
| 84 | |
| 85 | def _header(self) -> bytes: |
| 86 | return Packet.MAGIC + b"rcon" |
| 87 | |
| 88 | def encode(self, cmd: str) -> bytes: |
| 89 | return self._header() + f" {self.password} {cmd}".encode() |
| 90 | |
| 91 | |
| 92 | class ResponseBuilder(Packet): |
| 93 | """ |
| 94 | Class used to build and decode a response packet from multiple fragments. |
| 95 | |
| 96 | Attributes: |
| 97 | _fragments (bytearray): A bytearray to store the concatenated fragments. |
| 98 | |
| 99 | Methods: |
| 100 | _header() -> bytes: |
| 101 | Returns the header bytes that each fragment should start with. |
| 102 | |
| 103 | is_valid_fragment(fragment: bytes) -> bool: |
| 104 | Checks if the given fragment starts with the expected header. |
| 105 | |
| 106 | add_fragment(fragment: bytes): |
| 107 | Adds a fragment to the internal storage after removing the header. |
| 108 | |
| 109 | build() -> str: |
| 110 | Decodes and returns the concatenated fragments as a string. |
| 111 | """ |
| 112 | |
| 113 | def __init__(self): |
| 114 | self._fragments = bytearray() |
| 115 | |
| 116 | def _header(self) -> bytes: |
| 117 | return Packet.MAGIC + b"print\n" |
| 118 | |
| 119 | def is_valid_fragment(self, fragment: bytes) -> bool: |
| 120 | return fragment.startswith(self._header()) |
| 121 | |
| 122 | def add_fragment(self, fragment: bytes): |
| 123 | self._fragments.extend(fragment.removeprefix(self._header())) |
| 124 | |
| 125 | def build(self) -> str: |
| 126 | return self._fragments.decode() |
| 127 | |
| 128 | |
| 129 | def send(sock: socket.socket, request: Request, host: str, port: int, cmd: str) -> str: |
| 130 | """ |
| 131 | Send a single RCON (Remote Console) command to the server and return the response. |
| 132 | |
| 133 | This function sends a command to a game server using the RCON protocol over a UDP socket. |
| 134 | It waits for the server's response, collects it in fragments if necessary, and returns the complete response. |
| 135 | |
| 136 | Args: |
| 137 | sock (socket.socket): The UDP socket object used to send and receive data. |
| 138 | request (Request): An instance of the Request class used to encode the command. |
| 139 | host (str): The hostname or IP address of the server. |
| 140 | port (int): The port number on which the server is listening. |
| 141 | cmd (str): The RCON command to be sent to the server. |
| 142 | |
| 143 | Returns: |
| 144 | str: The complete response from the server after processing all received fragments. |
| 145 | |
| 146 | Raises: |
| 147 | socket.timeout: If the socket times out while waiting for a response from the server. |
| 148 | """ |
| 149 | sock.sendto(request.encode(cmd), (host, port)) |
| 150 | |
| 151 | response_builder = ResponseBuilder() |
| 152 | while True: |
| 153 | try: |
| 154 | data, _ = sock.recvfrom(4096) |
| 155 | except socket.timeout: |
| 156 | break |
| 157 | |
| 158 | if response_builder.is_valid_fragment(data): |
| 159 | response_builder.add_fragment(data) |
| 160 | |
| 161 | return response_builder.build() |
| 162 | |
| 163 | |
| 164 | def parse_args() -> argparse.Namespace: |
| 165 | parser = argparse.ArgumentParser() |
| 166 | parser.add_argument("--host", default="localhost") |
| 167 | parser.add_argument("--port", type=int, default=27960) |
| 168 | parser.add_argument("--password", default="secret") |
| 169 | parser.add_argument("--timeout", type=float, default=0.2) |
| 170 | parser.add_argument("--interactive", action="store_true") |
| 171 | parser.add_argument("cmd", nargs="?", default="status") |
| 172 | args = parser.parse_args() |
| 173 | return args |
| 174 | |
| 175 | |
| 176 | def main(): |
| 177 | """ |
| 178 | Main function to handle command-line arguments and interact with a remote server using RCON protocol. |
| 179 | This function parses command-line arguments, creates a UDP socket, and sends requests to a remote server. |
| 180 | It supports both interactive and non-interactive modes. |
| 181 | In non-interactive mode, it sends a single command to the server and prints the response. |
| 182 | In interactive mode, it continuously prompts the user for commands until the user quits by entering 'Q'. |
| 183 | Args: |
| 184 | None |
| 185 | Returns: |
| 186 | None |
| 187 | """ |
| 188 | |
| 189 | def cleaned_response(resp: str) -> str: |
| 190 | return re.sub(r"\^[0-9]", "", resp) |
| 191 | |
| 192 | args = parse_args() |
| 193 | |
| 194 | with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as sock: |
| 195 | sock.settimeout(args.timeout) |
| 196 | |
| 197 | request = Request(args.password) |
| 198 | |
| 199 | if not args.interactive: |
| 200 | if resp := send(sock, request, args.host, args.port, args.cmd): |
| 201 | print(cleaned_response(resp)) |
| 202 | return |
| 203 | |
| 204 | while cmd := input("cmd: ").strip(): |
| 205 | if cmd == "Q": |
| 206 | break |
| 207 | |
| 208 | if resp := send(sock, request, args.host, args.port, cmd): |
| 209 | print(cleaned_response(resp)) |
| 210 | |
| 211 | |
| 212 | if __name__ == "__main__": |
| 213 | main() |
| 214 |