Exemple #1
0
        private static void Main()
        {
            try
            {
                // Create a new instance of RconClient
                var rconClient = new RconClient();

                // Connect to the server at localhost:25575
                rconClient.Connect("localhost");

                // Login with password
                rconClient.Login("password");

                // Send command and get its output
                var cmdOutput = rconClient.SendCommand("list");

                // Print command output
                Console.WriteLine(cmdOutput);
            }
            catch (IncorrectPasswordException)
            {
                Console.WriteLine("Incorrect RCON password.");
            }
            catch (SocketException)
            {
                Console.WriteLine("A connection with the RCON server could not be established.");
            }

            // Keep console open until user presses any key
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }
Exemple #2
0
        static void Main(string[] args)
        {
            var appSettings = ConfigurationManager.AppSettings;
            var ipAddress   = appSettings["IpAddress"];
            var port        = int.Parse(appSettings["Port"]);
            var password    = appSettings["Password"];

            Console.WriteLine("Connecting to {0}:{1}", ipAddress, port);
            var rcon = new RconClient(ipAddress, port);

            Console.WriteLine("Authenticate");
            var response = rcon.Send(new AuthenticateCommand(password));

            FormatResponse(response);

            Console.WriteLine("Users");
            response = rcon.Send(new UsersCommand());
            FormatResponse(response);

            Console.WriteLine("Say");
            response = rcon.Send(new SayCommand("Hai!"));
            FormatResponse(response);

            Console.WriteLine("Status");
            response = rcon.Send(new StatusCommand());
            FormatResponse(response);

            Console.ReadKey();
        }
        public async Task <RconClient> GetClient()
        {
            if (this.connection == null)
            {
                return(null);
            }
            // touched
            await this.context.TouchConnection(this.connection);

            // Create an instance of RconClient pointing to an IP and a PORT
            var client = RconClient.Create(this.connection.Server, this.connection.Port.Value);

            await client.ConnectAsync();

            // Send a RCON packet with type AUTH and the RCON password for the target server
            var authenticated = await client.AuthenticateAsync(this.connection.Password);

            if (authenticated)
            {
                // If the response is positive, the connection is authenticated and further commands can be sent
                //var status = await client.ExecuteCommandAsync("status");
                // Some responses will be split into multiple RCON pakcets when body length exceeds the maximum allowed
                // For this reason these commands needs to be issued with isMultiPacketResponse parameter set to true
                // An example is CS:GO cvarlist
                //var cvarlist = await client.ExecuteCommandAsync("cvarlist", true);
                //var userList = await client.ExecuteCommandAsync("users");
                return(client);
            }
            return(null);
        }
Exemple #4
0
        /// <summary>
        /// Reinitialization
        /// </summary>
        /// <returns></returns>
        public async Task Reinit()
        {
            Console.WriteLine("Initializing ARK server " + name);
            //Set this up again.
            Console.WriteLine("Connecting via RCON...");
            rconConnection = new RconClient(new System.Net.IPEndPoint(System.Net.IPAddress.Parse(rconIp), ushort.Parse(rconPort.ToString())), rconPassword, new RconClient.ReadyCallback((RconClient context, bool okay) =>
            {
                Console.WriteLine("Connected to RCON.");
                bool isRconConnected = okay;
                if (!isRconConnected)
                {
                    Console.WriteLine("Failed to connect to the Ark server via RCON. Check to make sure it's running, or see if your settings are correct.");
                }

                //Set up the timer again
                timer          = new System.Timers.Timer(Program.arkUpdateTimeMs);
                timer.Elapsed += async(sender, e) => await Update();
                timer.Start();
                //Connect to Ark IO
                try
                {
                    arkIO = new ArkIOInterface("10.0.1.13", 13000, "password"); //Todo: Set this up in a custom  way.
                    if (!arkIO.client.client.Connected)
                    {
                        Console.WriteLine("Failed to connect to the Ark IO interface. Check the settings and try again.");
                    }
                }
                catch
                {
                    arkIO = null;
                    Console.WriteLine("Failed to connect to the Ark IO interface. Check the settings and try again.");
                }
            }));
        }
        static void Main(string[] args)
        {
            RconClient networkClient = new RconClient("127.0.0.1", 2310, "local");

            networkClient.Connected          += NetworkClient_Connected;
            networkClient.Disconnected       += NetworkClient_Disconnected;
            networkClient.MessageReceived    += NetworkClient_MessageReceived;
            networkClient.PlayerConnected    += NetworkClient_PlayerConnected;
            networkClient.PlayerDisconnected += NetworkClient_PlayerDisconnected;
            networkClient.PlayerRemoved      += NetworkClient_PlayerRemoved;
            networkClient.Connect();
            networkClient.WaitUntilConnected();

            bool requestSuccess = networkClient.Fetch(
                command: new GetPlayersRequest(),
                timeout: 5000,
                result: out List <Player> onlinePlayers);

            if (requestSuccess)
            {
                Console.WriteLine($"Players online: {onlinePlayers.Count}");
            }

            var bansFetchSuccess = networkClient.Fetch(new GetBansRequest(), 5000, out List <PlayerBan> bans);

            if (bansFetchSuccess)
            {
                Console.WriteLine($"{bans.Count} bans");
            }

            networkClient.Send(new SendMessageCommand("This is a global message"));

            Console.ReadLine();
        }
Exemple #6
0
        public async void RefreshAdminList()
        {
            log.Trace("RefreshAdminList(): Start");
            var qi = new RconQueueItem("bf2cc getadminlist", RconClient.RconState.AsyncCommand);

            RconClient.EnqueueCommand(qi);
            var lines = await qi.TaskCompletionSource.Task;

            AdminList.Clear();
            foreach (var line in lines)
            {
                var admins = reg_Admin.Match(line);
                if (admins.Success)
                {
                    var name = admins.Groups["name"].Value;
                    var ip   = admins.Groups["ip"].Value;
                    var port = int.Parse(admins.Groups["port"].Value);
                    Debug.WriteLine("Admin: " + name + " -> " + ip + ":" + port);
                    AdminList.Add(new AdminListItem()
                    {
                        Name = name, Address = ip, Port = port
                    });
                }
            }
            log.Trace("RefreshAdminList(): End (" + lines.Count + " admins)");
        }
Exemple #7
0
        private void LoadFromFile(string name, Tabs tabs)
        {
            Data.RemoteServerRcon serverData = new Data.RemoteServerRcon();
            XmlSerializer         serializer = new XmlSerializer(typeof(Data.RemoteServerRcon));
            StreamReader          reader     = new StreamReader(Utils.Main.RemoteDirectory + name + Path.DirectorySeparatorChar + "RconData.xml");

            serverData = (Data.RemoteServerRcon)serializer.Deserialize(reader);
            reader.Close();
            rcon = RconClient.INSTANCE;
            rcon.setupStream(serverData.adress, serverData.port, serverData.password);
            text.Clear();
            text.TextChanged += new EventHandler <TextChangedEventArgs>(Parsers.Log.Parse);
            foreach (Tab t in tabs.tabs)
            {
                if (t.control is RemoteConsole)
                {
                    RemoteConsole c = (RemoteConsole)t.control;
                    if (c.data == data)
                    {
                        tabs.SelectTab(t);
                        return;
                    }
                }
            }
            tabs.AddTab(name, this);
            logThread = new Thread(new ThreadStart(logThreadWork));
            logThread.Start();
        }
Exemple #8
0
        public GetAdminListCommand(RconClient rconClient)
        {
            RconClient = rconClient;
            AdminList  = new List <AdminListItem>();

            log.Debug("Loaded");
        }
        public GetAdminListCommand(RconClient rconClient)
        {
            RconClient = rconClient;
            AdminList = new List<AdminListItem>();

            log.Debug("Loaded");
        }
Exemple #10
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            error = "";

            try
            {
                Ftp.directoryListSimple(ftpData, "");
            }
            catch (WebException)
            {
                error = "ErrorFtp";
                return;
            }

            RconClient rcon = RconClient.INSTANCE;

            rcon.setupStream(rconData.adress, rconData.port, rconData.password);
            if (!rcon.isInit)
            {
                error = "ErrorRcon";
                return;
            }

            ftpData.Save();
            rconData.Save();
        }
Exemple #11
0
 public void Register(RconClient rconClient)
 {
     _rconClient = rconClient;
     rconClient.ServerInfoCommand.RoundStart       += ServerInfoCommandOnRoundStart;
     rconClient.ServerInfoCommand.RoundEnd         += ServerInfoCommandOnRoundEnd;
     rconClient.PlayerListCommand.PlayerUpdateDone += PlayerListCommandOnPlayerUpdateDone;
 }
Exemple #12
0
 public void Register(RconClient rconClient)
 {
     _rconClient = rconClient;
     _rconClient.ClientChatBufferCommand.CommandReceived += ClientChatBufferCommandOnCommandReceived;
     _rconClient.PlayerListCommand.PlayerLeft            += PlayerListCommandOnPlayerLeft;
     _rconClient.PlayerListCommand.PlayerUpdateDone      += PlayerListCommandOnPlayerUpdateDone;
 }
Exemple #13
0
        public void RconClientTest()
        {
            RconClient client = new RconClient();

            Assert.IsInstanceOfType(client, typeof(RconClient));
            Assert.IsFalse(client.IsConnected);
        }
Exemple #14
0
        public void ConnectTestWrongPassword()
        {
            RconClient client = new RconClient();

            Assert.IsTrue(client.Connect(Host, Port, "password"));
            Assert.IsTrue(client.IsConnected);

            client.Disconnect();
        }
Exemple #15
0
        protected virtual void OnNewClient(RconClient rconclient)
        {
            NewClientDelegate handler = NewClient;

            if (handler != null)
            {
                handler(this, rconclient);
            }
        }
Exemple #16
0
        public void ConnectTestWrongHost()
        {
            RconClient client = new RconClient();

            Assert.IsTrue(client.Connect("google.de", Port, Password));
            Assert.IsTrue(client.IsConnected);

            client.Disconnect();
        }
Exemple #17
0
        public void ConnectTestInvalidHost()
        {
            RconClient client = new RconClient();

            Assert.IsTrue(client.Connect("InvalidHost", Port, Password));
            Assert.IsTrue(client.IsConnected);

            client.Disconnect();
        }
Exemple #18
0
        static void Main(string[] args)
        {
            RconClient client = new RconClient(new System.Net.IPEndPoint(System.Net.IPAddress.Parse("10.0.1.13"), 32330), "ha", new RconClient.ReadyCallback((RconClient context, bool good) => {
                //We land here when we're ready
                Console.WriteLine(context.GetResponse("GetChat"));
                Console.WriteLine("Finished");
            }));

            Console.ReadLine();
        }
Exemple #19
0
        public void DisconnectTest()
        {
            RconClient client = new RconClient();

            Assert.IsTrue(client.Connect(Host, Port, Password));
            Assert.IsTrue(client.IsConnected);

            client.Disconnect();

            Assert.IsFalse(client.IsConnected);
        }
Exemple #20
0
        public void ExecuteLowPrioCommandAsyncTest()
        {
            RconClient client = new RconClient();

            Assert.IsTrue(client.Connect(Host, Port, Password));
            Assert.IsTrue(client.IsConnected);

            client.ExecuteLowPrioCommandAsync(new Rcon.Commands.ListPlayers(), (s, e) => Assert.IsTrue(e.Successful));

            client.Disconnect();
        }
        public async void RefreshClientChatBufferCommand()
        {
            log.Trace("RefreshClientChatBufferCommand(): Start");
            var qi = new RconQueueItem("bf2cc clientchatbuffer", RconClient.RconState.AsyncCommand);

            RconClient.EnqueueCommand(qi);
            var lines = await qi.TaskCompletionSource.Task;

            foreach (var line in lines)
            {
                var clientBuffer = reg_ClientBuffer.Match(line);
                if (clientBuffer.Success)
                {
                    var number    = clientBuffer.Groups["number"].Value;
                    var from      = clientBuffer.Groups["from"].Value;
                    var what      = clientBuffer.Groups["what"].Value;
                    var type      = clientBuffer.Groups["type"].Value;
                    var timestamp = clientBuffer.Groups["timestamp"].Value;
                    var message   = clientBuffer.Groups["message"].Value;
                    Debug.WriteLine(timestamp + " <" + from + "> " + message);
                    var item = new ChatHistoryItem()
                    {
                        Number    = int.Parse(number),
                        From      = from,
                        What      = what,
                        Type      = type,
                        TimeStamp = timestamp,
                        Message   = message
                    };
                    lock (ChatHistory)
                    {
                        ChatHistory.Add(item);
                        while (ChatHistory.Count > ChatHistorySize)
                        {
                            ChatHistory.RemoveAt(0);
                        }
                    }
                    OnChatLineReceived(item);

                    // Now check if its a command
                    var result = reg_Command.Match(item.Message);
                    if (result.Success)
                    {
                        var cmd = result.Groups["cmd"].Value.ToLower();
                        var p   = result.Groups["params"].Value;
                        p = Regex.Replace(p, @"\s\s+", " ");
                        var ps = p.Split(c_space);
                        OnCommandReceived(item, item.From, cmd, ps, p);
                    }
                }
            }
            log.Trace("RefreshClientChatBufferCommand(): End (" + lines.Count + " chat lines)");
        }
Exemple #22
0
        protected async Task <string> ExecuteCommandAsync(string command)
        {
            var client = RconClient.Create(_address, _port);
            await client.ConnectAsync();

            if (!await client.AuthenticateAsync(_password))
            {
                throw new AuthenticationException();
            }

            return(await client.ExecuteCommandAsync(command));
        }
Exemple #23
0
        public async Task SendMessageShouldReceiveAResponse()
        {
            // Arrange
            var channel    = new FakeChannel();
            var rconClient = RconClient.Create(channel);
            await rconClient.ConnectAsync();

            // Act
            var response = await rconClient.ExecuteCommandAsync("test echo");

            // Assert
            Assert.Equal("Command executed", response);
        }
Exemple #24
0
        public async Task AuthenticateShouldWorkOnStrictRCONServers(string password, bool isAuthenticated)
        {
            // Arrange
            var channel    = new SourceChannel();
            var rconClient = RconClient.Create(channel);
            await rconClient.ConnectAsync();

            // Act
            var response = await rconClient.AuthenticateAsync(password);

            // Assert
            Assert.Equal(isAuthenticated, response);
        }
Exemple #25
0
        public async Task MultiPacketResponseShouldBeCorrectlyReceivedFromStrictRCONServers()
        {
            // Arrange
            var channel    = new SourceChannel();
            var rconClient = RconClient.Create(channel);
            await rconClient.ConnectAsync();

            // Act
            var response = await rconClient.ExecuteCommandAsync("print all", true);

            // Assert
            Assert.Equal("This will be a very long message", response);
        }
Exemple #26
0
        public void Register(RconClient rconClient)
        {
            _rconClient = rconClient;
            //_rconClient.PlayerListCommand.PlayerUpdated += PlayerListCommandOnPlayerUpdated;
            _rconClient.PlayerListCommand.PlayerUpdateDone += PlayerListCommandOnPlayerUpdateDone;
            _rconClient.PlayerListCommand.PlayerLeft       += PlayerListCommandOnPlayerLeft;
            _rconClient.PlayerListCommand.PlayerJoined     += PlayerListCommandOnPlayerJoined;

            //DatabaseController.Initialize();
            //_playerStorage = new PlayerStorage();

            OnRegistered(this);
        }
 public AdminCore()
 {
     //TODO: check EnableRuntime before creating these objects to save memory
     Database = new SQLHandler(this);
     Server   = new ServerManager(this);
     WebAdmin = new WebServer(this);
     Rcon     = new RconClient(this);
     Players  = new PlayerHandler(this);
     Announce = new AnnounceHandler(this);
     Game     = new GameHandler(this);
     Commands = new CommandDispatcher(this);
     Mods     = new LvlWriter(this);
     Plugins  = new PluginManager(this);
 }
Exemple #28
0
        private async Task MainAsync()
        {
            var config = new RconClientConfiguration("127.0.0.1", 7600);

            try
            {
                using (var client = new RconClient(config))
                {
                    await client.ConnectAsync();

                    await client.StartClientAsync();

                    if (client.Socket.Connected)
                    {
                        if (await client.AuthenticateAsync("test"))
                        {
                            _ = Task.Factory.StartNew(async() =>
                            {
                                while (true)
                                {
                                    await client.ExecuteCommandAsync <RconResultPacket>("string ping");
                                    await Task.Delay(1000);
                                    Console.WriteLine(client.QueuedPackets.Count);
                                }
                            });

                            Console.WriteLine("Authentication successful!");
                            while (true)
                            {
                                var inp    = Console.ReadLine();
                                var result = await client.ExecuteCommandAsync <RconResultPacket>(inp);

                                Console.WriteLine(result.Result);
                            }
                        }
                        else
                        {
                            Console.WriteLine("Authentication failed!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

            Console.ReadLine();
        }
Exemple #29
0
        private async void DoConnect()
        {
            if (RconClient != null)
            {
                RconClient.Dispose();
            }

            Dispatcher.Invoke(() => Players.Clear());
            RconClient = new RconClient();

            RconClient.Disconnected += RconClientOnDisconnected;

            RconClient.PlayerListCommand.PlayerJoined += RconClientOnPlayerJoined;
            RconClient.PlayerListCommand.PlayerLeft   += RconClientOnPlayerLeft;
            RconClient.ServerInfoCommand.RoundStart   += ServerInfoCommandOnRoundStart;
            RconClient.Connected += RconClientOnConnected;
            await RconClient.Connect(Config.RconServerAddress, Config.RconServerPort, Config.RconServerPassword);
        }
Exemple #30
0
        public async Task CanceledResponseShouldDisconnectTheClient()
        {
            // Arrange
            var channel = new FakeChannel();

            channel.CancelNextReponse();
            var rconClient = RconClient.Create(channel);
            await rconClient.ConnectAsync();

            var tcs = new TaskCompletionSource <bool>();

            rconClient.ConnectionClosed += () =>
            {
                tcs.SetResult(true);
            };

            // Act Assert
            await Assert.ThrowsAsync <TaskCanceledException>(() => rconClient.ExecuteCommandAsync("test echo"));

            Assert.True(await tcs.Task);
        }
Exemple #31
0
        public static bool IsServerResponding(ArkServerInfo Server)
        {
            bool       serverIsRunning = false;
            RconClient client          = new RconClient();

            try
            {
                client.Connect(Server.IPAddress, Int32.Parse(Server.RCONPort), Server.ServerPassword);
                if (client.IsConnected)
                {
                    serverIsRunning = true;
                }
            }
            catch (Exception ex)
            {
                serverIsRunning = false;
                //Console.WriteLine(DateTime.Now + ": " + Server.Name + " Exception:"  + ex.Message);
                Methods.Log(Server, DateTime.Now + ": " + Server.Name + " Exception:" + ex.Message);
            }
            client.Disconnect();


            return(serverIsRunning);
        }
 public ClientChatBufferCommand(RconClient rconClient)
 {
     RconClient = rconClient;
     ChatHistory = new List<ChatHistoryItem>();
     log.Debug("Loaded");
 }
 public PlayerListCommand(RconClient rconClient)
 {
     RconClient = rconClient;
 }
 public SimpleCommand(RconClient rconClient)
 {
     RconClient = rconClient;
 }
        static void Main(string[] args)
        {
            // Check if some settings not set in the app.config
            if (string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["RCONServerIP"]) || string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["RCONServerPort"]) || string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["RCONServerPassword"]) || string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["WebservicePort"]) || string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["WebserviceAdminUsername"]) || string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["WebserviceAdminPassword"]) || string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["WebserviceHost"]))
            {
                Console.WriteLine("Some settings in app.config is not set");
                Console.WriteLine(">> Press any key to quit <<");
                Console.ReadLine();
            }
            else
            {
                // Get server settings from app.config
                serverIP = System.Configuration.ConfigurationManager.AppSettings["RCONServerIP"];
                serverPort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["RCONServerPort"]);
                serverPassword = System.Configuration.ConfigurationManager.AppSettings["RCONServerPassword"];
                webserviceHost = System.Configuration.ConfigurationManager.AppSettings["WebserviceHost"];
                webservicePort = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["WebservicePort"]);

                // Setup the rcon client with events etc and connect
                rconClient = new RconClient();
                rconClient.Address = serverIP;
                rconClient.Port = serverPort;
                rconClient.Connected += new EventHandler(rconClient_Connected);
                rconClient.ConnectError += new EventHandler<ConnectErrorEventArgs>(rconClient_ConnectError);
                rconClient.Disconnected += new EventHandler<DisconnectedEventArgs>(rconClient_Disconnected);
                rconClient.LevelLoaded += new EventHandler<LevelLoadedEventArgs>(rconClient_LevelLoaded);
                rconClient.LoggedOn += new EventHandler(rconClient_LoggedOn);
                rconClient.PlayerAuthenticated += new EventHandler<PlayerAuthenticatedEventArgs>(rconClient_PlayerAuthenticated);
                rconClient.PlayerChat += new EventHandler<PlayerChatEventArgs>(rconClient_PlayerChat);
                rconClient.PlayerJoined += new EventHandler<PlayerEventArgs>(rconClient_PlayerJoined);
                rconClient.PlayerJoining += new EventHandler<PlayerJoiningEventArgs>(rconClient_PlayerJoining);
                rconClient.PlayerKilled += new EventHandler<PlayerKilledEventArgs>(rconClient_PlayerKilled);
                rconClient.PlayerLeft += new EventHandler<PlayerEventArgs>(rconClient_PlayerLeft);
                //rconClient.PlayerMoved += new EventHandler<PlayerMovedEventArgs>(rconClient_PlayerMoved);
                rconClient.PlayerSpawned += new EventHandler<PlayerEventArgs>(rconClient_PlayerSpawned);
                rconClient.PunkBusterMessage += new EventHandler<PunkBusterMessageEventArgs>(rconClient_PunkBusterMessage);
                rconClient.RawRead += new EventHandler<RawReadEventArgs>(rconClient_RawRead);
                rconClient.Response += new EventHandler<ResponseEventArgs>(rconClient_Response);
                rconClient.RoundOver += new EventHandler(rconClient_RoundOver);
                rconClient.Connect();

                // Setup a timer for every 5 seconds to run the listplayers function that do stuff with the players, like commands etc.
                aTimer = new System.Timers.Timer(5000);
                aTimer.Elapsed += new ElapsedEventHandler(DoPlayerCommands);
                aTimer.Enabled = true;

                // Start the webservice/HTTP Listener to listen on webservice port
                Webservice.Start(webserviceHost, webservicePort);

                // Add some handling of ctrl+c so we stoping the webservice right
                Console.TreatControlCAsInput = false;  // Turn off the default system behavior when CTRL+C is pressed.
                Console.CancelKeyPress += delegate(object sender, ConsoleCancelEventArgs eventArgs)
                {
                    Webservice.Stop();
                };

                Console.ReadLine();
            }
        }
 public ServerInfoCommand(RconClient rconClient)
 {
     RconClient = rconClient;
     ServerInfo = new ServerInfo();
 }