def run_server(self) -> ContextManager[MCRcon]: server_process = Popen( ["java", "-jar", self.server_path.name, "--nogui"], cwd=self.server_dir) # There must be a better way rcon = None for i in range(72): sleep(5) try: rcon = MCRcon("localhost", self.RCON_PASSWORD, int(self.RCON_PORT)) # tries to create a connection with rcon: pass break except ConnectionError: continue else: server_process.kill() pytest.fail( "Could not connect to the minecraft server after 5 minutes") with rcon: try: yield rcon finally: rcon.command("stop") server_process.wait(30)
def __init__(self, ip_address, port, password, name="None"): self.con = MCRcon(ip_address, password, port=port) self.name = name try: self.con.connect() except ConnectionRefusedError: print(f'rcon failed to connect {self.con.host}:{self.con.port}')
def __init__(self, serverUrl, localIp, rconPort, queryPort, rconPassword): self.serverUrl = serverUrl self.localServer = MinecraftServer(localIp, queryPort) self.urlServer = MinecraftServer(serverUrl, queryPort) self.rcon = MCRcon(localIp, rconPassword, port=rconPort) self.previousPlayerAmountOnline = None self.rconConnect()
def __init__(self, host, port: int, password, use_tls: bool = True): tls = { True: 1, False: 0 } self.__auto_close_timer = AsyncCountdownTimer(self.__disconnect_seconds, self.__disconnect) self.__con = MCRcon(host, password, port, tls[use_tls])
class Connection: def __init__(self, address, port, secret): self.mcr = MCRcon(address, secret) self.mcr.connect() def send(self, msg): resp = self.mcr.command(msg) return resp
def __init__(self, mcrcon_host, mcrcon_password, mcrcon_port, fps): self.timeout = 1 / int(fps) self.mcrcon = MCRcon(mcrcon_host, mcrcon_password, mcrcon_port) self.online_players = [] self.message = {} self.refresh_rcon() threading.Thread(target=self.get_message).start()
def __init__(self, client): self.client = client self.rcon_smp = MCRcon(config_rcon['rcon_smp']['rcon-ip'], config_rcon['rcon_smp']['rcon-password'], config_rcon['rcon_smp']['rcon-port']) self.coords = () self.peri_size = 0 self.worldeater_crashed = False self.we_updates = False self.ylevel = 0
class RconInterface: def __init__(self, ip_address, port, password, name="None"): self.con = MCRcon(ip_address, password, port=port) self.name = name try: self.con.connect() except ConnectionRefusedError: print(f'rcon failed to connect {self.con.host}:{self.con.port}') def getstatus(self): return str(self.con.socket).find("0.0.0.0") == -1 def reconnect(self): if not self.getstatus(): self.con.connect() def command(self, command, retrys=0): try: return self.con.command(command) except (ConnectionResetError, ConnectionRefusedError): self.con.connect() if retrys < 5: self.command(command, retrys + 1) def __del__(self): self.con.disconnect()
def __init__(self, host=None, password=None): if host is not None and password is not None: self._host = host self._password = password self._client = MCRcon(host, password) self.connect() else: self._host = None self._password = None self._client = None self._adv_file, self.adv_categories = self._load_advancements()
def connect(self): if self._client is None: if self._host is not None and self._password is not None: self._client = MCRcon(self._host, self._password) else: self.set_host(input("Enter Host IP: ")) self.set_password(input("Enter Password: ")) self._client = MCRcon(self._host, self._password) self._client.connect() else: self._client.connect()
def rcon_command(self,command): if self.rcon == None: self.rcon = MCRcon(os.environ['RCON_HOST'],os.environ['RCON_PASSWORD'],port=int(os.environ['RCON_PORT'])) self.rcon.connect() try: response = self.rcon.command(command) except BrokenPipeError: print("Lost RCON Connection, trying to reconnect") self.rcon.connect() response = self.rcon.command(command) return response
def __init__(self, bot: DioCraft): super().__init__() self.mcr = MCRcon(server_ip, server_password, int(server_port)) try: self.mcr.connect() except: print("Unexpected error: {}".format(sys.exc_info()[0])) self.mcr.disconnect() self.bot = bot
def __init__(self): prefix="/home/jiba/Minecraft/server" self.statsdirectory = prefix+"/world/stats" self.playerdirectory = prefix+"/world/playerdata" self.advancementsdirectory = prefix+"/world/advancements" self.betterquesting = prefix+"/world/betterquesting" self.map = dict() self.questsEnabled = False if all(x in os.environ for x in ['RCON_HOST','RCON_PASSWORD']): self.mcr = MCRcon(os.environ['RCON_HOST'],os.environ['RCON_PASSWORD'],port=int(os.environ['RCON_PORT'])) self.mcr.connect() if os.path.isdir(self.betterquesting): self.questsEnabled = True
async def msg(self, ctx, msg=None, player=None): """ Message server or a specific player """ if player is None: with MCRcon(host=self.host, password=self.rcon_pwd, port=self.rcon_port) as mcr: mcr.command(f"say {msg}") await ctx.channel.send(f"Messaged Minecraft server") else: with MCRcon(host=self.host, password=self.rcon_pwd, port=self.rcon_port) as mcr: resp = mcr.command(f"tell {player} {msg}") await ctx.channel.send(f"Server response: {resp}")
def send_commands(server_ip, rcon_password, commands, buyer, rcon_port): server_ip = str(server_ip).split(':')[0] mcr = MCRcon(server_ip, rcon_password, int(rcon_port)) mcr.connect() for command in commands: mcr.command(command.replace("{PLAYER}", buyer)) mcr.disconnect()
class _RConsole: __lock_connection_action = Lock() __lock_auto_close_thread = Lock() __disconnect_seconds = 100 def __init__(self, host, port: int, password, use_tls: bool = True): tls = { True: 1, False: 0 } self.__auto_close_timer = AsyncCountdownTimer(self.__disconnect_seconds, self.__disconnect) self.__con = MCRcon(host, password, port, tls[use_tls]) def execute(self, command: str, timeout: int = 0) -> str: """ Execute a command, return its response. :param command: the command to be executed. :param timeout: timeout in seconds. If it is set to 0, the function waits until a response is received. If timed out, an `TimedOutException` will be thrown. :return: the response echo. """ # check connection with self.__lock_connection_action: if not self.__con.socket: self.__con.connect() with self.__lock_auto_close_thread: self.__auto_close_timer.reset() self.__auto_close_timer = AsyncCountdownTimer(self.__disconnect_seconds, self.__disconnect) self.__auto_close_timer.start() # TODO: implement timeout if timeout: raise NotImplementedError("Sorry, timeout has not been implemented") # execute command logging.info(f'Execute command: {command}') return self.__con.command(command) def __del__(self): if self.__auto_close_timer: self.__auto_close_timer.reset() def __disconnect(self): disconnected = False with self.__lock_connection_action: if self.__con.socket: self.__con.disconnect() disconnected = True if disconnected: logging.info('Console is inactive. Disconnected from RCON server.')
def test_login(server, tmp_path): """Assert that the client is able to log in properly""" with MCRcon(server.host, server.rcon_password, server.rcon_port) as mcr: response = mcr.command("/list") assert FISHING_USERNAME not in response with ManagedClient(tmp_path, server): time.sleep(1) # Ensure we have time to login with MCRcon(server.host, server.rcon_password, server.rcon_port) as mcr: response = mcr.command("/list") assert FISHING_USERNAME in response
def connectToServer(self, serv_ip, rcon_port, rcon_pass): self.ip = serv_ip try: self.port = int(rcon_port) except ValueError: messagebox.showerror("Server Connectivity - ERROR", "The Minecraft Server RCON port must be an integer (1-65535)") raise ValueError("The Minecraft Server RCON port must be an integer (1-65535)") self.mcr_instance = MCRcon(host=self.ip, port=self.port, password=rcon_pass) self.mcr_instance.connect() if self.mcr_instance: messagebox.showinfo("Server Connectivity - Success", "Successfully connected to the server!") self.resetWindow() self.generate_main_ui() else: messagebox.showinfo("Server Connectivity - Failed", "Failed connecting to the server!")
def update_mc(): """ Update Rcon and Query with configuration """ global mcr, mcq mcr = MCRcon(conf["Server ip"], conf["Rcon passwd"], conf["Rcon port"]) mcq = MinecraftServer(conf["Server ip"], conf["Query port"])
async def rcon(session: CommandSession): cmmd = session.get('cmmd', prompt='请输入指令') with MCRcon(host=session.bot.config.RCON_HOST, port=session.bot.config.RCON_PORT, password=session.bot.config.RCON_PWD) as rcon: res = rcon.command(cmmd) await session.send(res)
async def console(self, ctx, command: str, *, values=None): if await self.config.guild(ctx.guild).setup_complete() == True: try: with MCRcon( str(await self.config.guild(ctx.guild).server_ip()), str(await self.config.guild(ctx.guild).rcon_password()), int(await self.config.guild(ctx.guild).rcon_port())) as mcr: if values != None: returned = mcr.command(f"{command} {values}") await ctx.send( f"**Executed Command:** `/{command} {values}`") await ctx.send(f"**Returned:** {returned}") else: returned = mcr.command(f"{command}") await ctx.send(f"**Executed Command:** `/{command}`") await ctx.send(f"**Returned:** {returned}") except (ConnectionRefusedError, TimeoutError, MCRconException) as e: await ctx.send( f"Connection failed with error ```{e}``` The server may be down/restarting please try again in a couple of minutes.\nIf not, make sure that your details to connect to the server again are correct. You may want to run the [p]mcsetup process again." ) else: await ctx.send( f"Please complete setup using `{ctx.prefix}mcsetup` before using this command" )
def test_catches_fish(server, tmp_path, setup_spawn): OBJECTIVE_NAME = "fish_caught" setup_for_fishing(tmp_path, server) with MCRcon(server.host, server.rcon_password, server.rcon_port) as mcr: mcr.command(f"/scoreboard objectives remove {OBJECTIVE_NAME}") mcr.command(f"/scoreboard objectives add {OBJECTIVE_NAME} " "minecraft.custom:minecraft.fish_caught") mcr.command( f"/scoreboard objectives setdisplay sidebar {OBJECTIVE_NAME}") with ManagedClient(tmp_path, server) as client_process: # Poll the amount of fish caught once every tick for 60 seconds for i in range(20 * 60): response = mcr.command( f"/scoreboard players get {FISHING_USERNAME} {OBJECTIVE_NAME}" ) # Can't get the value for the objective before the player has caught one if (f"Can't get value of {OBJECTIVE_NAME} for {FISHING_USERNAME}" not in response): # Make sure we get the expected output assert f"{FISHING_USERNAME} has 1 [{OBJECTIVE_NAME}]" in response break time.sleep(1 / 20) stdout, stderr = client_process.communicate() assert "Caught one!" in stdout
def rcon_command(command: str): try: with MCRcon(host=RCON_HOST, password=RCON_PASSWORD, port=RCON_PORT) as rcon: return rcon.command(f"/{command}") except (MCRconException, OSError) as e: logging.error(f"Connection to RCON failed: {e}")
async def whitelist(ctx, minecrafter: str): with MCRcon(os.getenv('SERVER_HOST'), os.getenv('SERVER_PASS')) as mcr: resp = mcr.command("/whitelist add " + minecrafter) print(resp) msg = "Whitelisted " + minecrafter + "! They can now connect to the server".format( ctx.message) await ctx.send(msg)
async def exec(self, ctx, *, command=None): if utils.is_admin(ctx.message.author.id): try: if command: with MCRcon("rumblur.hrebeni.uk", secret.rcon_password, secret.rcon_port) as mcr: response = mcr.command(command) # BadCoder pretty_response = re.sub( '(§[0-9a-fA-Fkmorln])|(§\[#[0-9a-fA-F]{1,6}])|(§$)', '', response) if len(response) <= 1800: await ctx.send(f"Ответ: ```{pretty_response}```") elif len(response) <= 0: await ctx.send("`Пустой ответ`") else: await ctx.send("`Ответ был слишком большим.`", file=discord.File( BytesIO(response.encode()), "response.txt")) else: await ctx.send( 'Использование: `,exec "command без /, как в консоли"`' ) except Exception as e: await ctx.send(f"`{e}`") else: await ctx.send(embed=await admin_notice())
def v1_minecraft_whitelist(): sample = { "add": { "required": False, "allowed_types": [str] }, "remove": { "required": False, "allowed_types": [str] } } query = request.args.to_dict(flat=True) succ, errors = check(sample, query) if not succ: return make_response(jsonify(errors), 400) host = config.get_setting("minecraft-server-host", "127.0.0.1") port = config.get_setting("minecraft-server-rcon-port", 25575) password = config.get_setting("minecraft-server-password", "password") responses = list() with MCRcon(host, password, port=port) as mcr: if "add" in query: responses.append(mcr.command(f"whitelist add {query['add']}")) if "remove" in query: responses.append( mcr.command(f"whitelist remove {query['remove']}")) return make_response(jsonify(responses), 200)
def main(): if len(sys.argv) < 2: print("Usage: {port} {password}") return port = int(sys.argv[1]) password = sys.argv[2] with MCRcon("127.0.0.1", password, port=port) as mcr: print("Connected. Showing warning...") warnCommand = "tellraw @a [\"[\",{\"text\":\"McServerManager\",\"color\":\"blue\"},\"]: Server will shut down in \",{\"text\":\"10\",\"color\":\"red\"},\" seconds\"]" mcr.command(warnCommand) print("Sent warning, sleeping for 10 seconds...") time.sleep(10) print("Sleep done. Running /stop command") resp = mcr.command("stop") print("Stop command sent") print("Server responded with:", resp) time.sleep(2)
def rcon(self, command): try: with MCRcon(self.host, self.password, self.port) as mcr: return mcr.command(command) except ConnectionRefusedError: print("Minecraft: ConnectionRefusedError") return ""
async def loop_func(self): if self.looping: with MCRcon("127.0.0.1", PASSW) as mcr: resp = mcr.command('/execute at @e[type=arrow,nbt={inGround:1b,pickup:2b}] run fill ~0 ~0 ~0 ~0 ~0 ~0 lava') resp = mcr.command('/kill @e[type=arrow,nbt={inGround:1b}]') #print (resp) mcr.disconnect()
def datapack(*args): try: with MCRcon(config['serverIP'], config['rconPASS']) as mcr: if len(args) == 1: response = mcr.command("datapack " + args[0]) btext.debug(args) btext.debug("1") btext.info(response) elif len(args) == 2: response = mcr.command("datapack " + args[0] + ' "' + args[1] + '"') btext.debug(args) btext.debug("2") btext.info(response) elif len(args) == 3: response = mcr.command("datapack " + args[0] + ' "' + args[1] + '" ' + args[2]) btext.debug(args) btext.debug("3") btext.info(response) elif len(args) == 4: response = mcr.command("datapack " + args[0] + ' "' + args[1] + '" ' + args[2] + ' "' + args[3] + '"') btext.debug(args) btext.debug("4") btext.info(response) except Exception as e: btext.debug(e) btext.error( "Something fucky happened while trying to use {}".format( inspect.stack()[0][3]))
def main(): if platform.system() == "Windows": clear_str = 'cls' else: clear_str = 'clear' parser = argparse.ArgumentParser(description="Send commands to a remote Minecraft console") parser.add_argument('-ip','--host',help="IP address of the server",required=True) parser.add_argument('-p','--port',help="Port for RCON on the server",required=True) args = parser.parse_args() pw = getpass.getpass() rcon = MCRcon(args.host,int(args.port),pw) print("Type 'cls' or 'clear' to clear the screen") print("Type 'exit' or 'quit' or cntrl-c to exit") while 1: try: cmd = input('Remote Console>> ') if cmd.strip().lower() in ['cls', 'clear']: os.system(clear_str) elif cmd.strip().lower() in ['exit', 'quit']: rcon.close() exit(0) elif cmd.strip() == "": pass else: msg = rcon.send(cmd) #for line in msg.split('/'): # print(line) print(msg) except EOFError: print() exit(0)
def run_command(self, command): rcon = MCRcon(self.host, self.rcon_port, self.password) rcon.send(command) rcon.close()