#! /usr/bin/env python3 # -*- coding: utf-8 -*- # LinuxGSM rcon.py module # Author: MicLieg # Contributors: http://linuxgsm.com/contrib # Website: https://linuxgsm.com # Description: Allows sending RCON commands to different gameservers. import argparse import socket import struct import sys class PacketTypes: LOGIN = 3 COMMAND = 2 class Rcon: def __init__(self, arguments): self.arguments = arguments self.connection = None def __enter__(self): self.connect_to_server() return self def __exit__(self, exc_type, exc_val, exc_tb): if self.connection: self.connection.close() @staticmethod def fatal_error(error_message, error_code): sys.stderr.write(f'ERROR: {error_code} {error_message}\n') sys.exit(error_code) @staticmethod def exit_success(success_message=''): sys.stdout.write(f'OK: {success_message}\n') sys.exit(0) def connect_to_server(self): self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.settimeout(self.arguments.timeout) try: self.connection.connect((self.arguments.address, self.arguments.port)) except socket.timeout: self.fatal_error('Request timed out', 1) except Exception as e: self.fatal_error(f'Unable to connect: {e}', 1) def send_packet(self, request_id, packet_type, data): # Packet structure follows the Source RCON Protocol: size, request ID, type, data, two null bytes packet = ( struct.pack('