/// <summary> /// Sends a RCON command to a server /// </summary> /// <param name="command">Command to send</param> /// <param name="server">3 letter server code</param> /// <returns>Output from RCON command</returns> public async Task <string> RconCommand(string command, Server server) { string reply = null; //Get the bots IP, typically my IP string botIp = new WebClient().DownloadString("http://icanhazip.com").Trim(); IPHostEntry iPHostEntry = null; try { iPHostEntry = Dns.GetHostEntry(server.address); } catch { return("HOST_NOT_FOUND"); } //Setup new RCON object using (var rcon = new RCON(IPAddress.Parse($"{iPHostEntry.AddressList[0]}"), 27015, server.rcon_password)) { //Send the RCON command to the server reply = await rcon.SendCommandAsync(command); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"{DateTime.Now}\nRCON COMMAND: {server.address}\nCommand: {command}\n"); Console.ResetColor(); } //Remove the Bot's public IP from the string. reply = reply.Replace($"{botIp}", "69.420.MLG.1337"); return(reply); }
public async Task Initialize() { _rcon = new RCON(IPAddress.Parse(_config.Ip), (ushort)_config.RconPort, _config.RconPassword); _rcon.OnDisconnected += _rcon_OnDisconnected; await Connect(); }
public async void ConsoleControl() //控制台 { LogUpdate("\n正在尝试连接至RCON服务器...", null, null); try { RCON rcon = new RCON(IPAddress.Parse(IP_address), Port, Password); await rcon.ConnectAsync(); Title = "ASM - 管理: " + IP_address + ':' + Port.ToString(); LogUpdate("\nRCON服务器已成功连接 IP:" + IP_address + " Port:" + Port.ToString(), null, null); LogUpdate("\n正在尝试打开玩家检测器...", null, null); Task PlayerUpdate = Task.Run(() => { Application.Current.Dispatcher.Invoke((Action)(() => { PlayerNumUpdate(); })); }); LogUpdate("\n玩家检测器已开启", null, null); LogUpdate("\n", null, null); } catch (AuthenticationException) { MessageExt.Instance.ShowDialog("您的RCON连接密码无法通过验证, 请检查输入的密码是否正确", "错误"); } }
async public Task <string> RconCommand(string command, JsonServer server) { string reply = null; string botIP = new WebClient().DownloadString("http://icanhazip.com").Trim(); IPHostEntry iPHostEntry = null; try { iPHostEntry = Dns.GetHostEntry(server.Address); } catch { return("HOST_NOT_FOUND"); } var rcon = new RCON(IPAddress.Parse($"{iPHostEntry.AddressList[0]}"), 27015, server.Password, 1000); reply = await rcon.SendCommandAsync(command); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine($"RCON COMMAND: {server.Address}\nCommand: {command}\n"); Console.ResetColor(); //If you re-set the rcon_password all RCON connections are closed. //By not awaiting this, we are able to set the rcon password back to the same value closing the connection. //This will automatically timeout and dispose of the rcon connection when it tries to conncect again. Task fireAndForget = rcon.SendCommandAsync($"rcon_password {server.Password}"); reply = reply.Replace($"{botIP}", "69.420.MLG.1337"); //Remove the Bot's public IP from the string. return(reply); }
static async Task minecraft() { var serveraddress = IPAddress.Parse("127.0.0.1"); //IPアドレスとして扱うための変換 var serverpass = "******"; //RCONでログインするためのパスワード ushort port = 25575; //サーバのポート番号 var command = "/weather clear"; // コマンド //CoreRCONを使ってMinecraftへ接続 try { //var connection = new RCON(serveraddress, port, serverpass); var connection = new RCON(serveraddress, port, serverpass); //コマンドの送信 var result = await connection.SendCommandAsync(command); //ログの受信 Console.WriteLine(result); } catch (Exception e) { Console.WriteLine(e); return; } }
/// <summary> /// Gets an already connect RCON client, or makes a new one /// </summary> /// <param name="serverId">Server ID to get client for</param> /// <returns>RCON client</returns> private async Task <RCON> GetOrCreateRconClient(string serverId) { if (!_rconClients.ContainsKey(serverId)) { //Validate server before adding var server = DatabaseUtil.GetTestServer(serverId); //Server cannot be null. if (server == null) { throw new NullReferenceException(nameof(serverId)); } var ipEndPoint = GeneralUtil.GetIpEndPointFromString(server.Address); var rconClient = new RCON(ipEndPoint.Address, (ushort)ipEndPoint.Port, server.RconPassword); _rconClients.Add(serverId, rconClient); rconClient.OnDisconnected += () => { _ = _log.LogMessage($"RCON client for `{serverId}` has been disposed.", false, color: LOG_COLOR); if (_rconClients.ContainsKey(serverId)) { _rconClients.Remove(serverId); } }; rconClient.OnLog += logMessage => { _ = _log.LogMessage(logMessage, color: LOG_COLOR); }; } return(_rconClients[serverId]); }
internal async Task Connect() { _logger.Debug("Connecting to RCON interface..."); var settings = _configuration.Factorio.Rcon; var address = IPAddress.Parse("127.0.0.1"); _rcon = new RCON(address, (ushort)settings.Port, settings.Password); _rcon.OnDisconnected += () => { _logger.Error("RCON interface unexpectedly disconnected!"); OnDisconnect?.Invoke(this, EventArgs.Empty); }; // await _rcon.ConnectAsync(); // Should be unecessary var response = await _rcon.SendCommandAsync("/version"); _logger.Information($"Got version response: {response}"); await _producer.Produce(KafkaTopics.EVENTS, new FactoryOnlineEvent(_configuration.Factorino.FactoryId)); _logger.Information($"Factory Online! Starting RCON poll.."); _pollTimer.Start(); }
public async Task <IActionResult> ExecuteRconCommand(Guid serverId) { // TODO: Put this somewhere sensible // TODO: Handle non-Minecraft servers // TODO: Figure out how to stream responses and events var server = await _servers.GetServerByIdAsync(serverId); var config = server.DeserialiseConfiguration() as MinecraftConfiguration; var containerPort = config.RconContainerPort; // TODO: Is this reliable? var container = server .Containers .Find(c => c.ServerPorts.Any(p => p.ContainerPort == containerPort)); if (container == null) { // TODO: Remove this once the Rcon port is properly exposed container = server.Containers.First(); } // TODO: Don't hardcode this var ipAddresses = await Dns.GetHostAddressesAsync($"TRICERATOPS_{container.Name}"); var rcon = new RCON(ipAddresses[0], containerPort, "testing"); await rcon.ConnectAsync(); string help = await rcon.SendCommandAsync("help"); return(Json($"We got help from the server: {help}")); }
public async Task ClientInfo(string player) { _logger.LogInformation("clientinfo called"); if (!PickupHelpers.IsInPickupChannel((IGuildChannel)Context.Channel)) { return; } if (string.IsNullOrWhiteSpace(_rconPassword) || string.IsNullOrWhiteSpace(_rconHost) || _rconPort == 0) { return; } var userdata = await RCON.UDPSendCommand($"dumpuser {player}", _rconHost, _rconPassword, _rconPort).ConfigureAwait(false); if (userdata.IndexOf("is not on the server", StringComparison.OrdinalIgnoreCase) != -1) { await Context.Message.ReplyAsync( $"```{Environment.NewLine}" + $"{userdata}" + $"{Environment.NewLine}```"); return; } var clientInfo = new ClientInfo(userdata); await Context.Message.ReplyAsync( $"```{Environment.NewLine}" + $"{clientInfo.ToTable()}" + $"{Environment.NewLine}```"); }
public Messages() { Discord = new Discord(); Twitch = new Twitch(); RCON = new RCON(); AnnounceIntervalInMinutes = 0; }
private async Task <RCON> GetOrCreateRconClient(string serverID) { if (!_rconClients.ContainsKey(serverID)) { var server = await DatabaseModule.GetTestServerInfo(serverID); if (server == null) { throw new NullReferenceException(nameof(serverID)); } var ipEndPoint = GeneralUtil.GetIpEndPointFromString(server.Address); var rconClient = new RCON(ipEndPoint.Address, (ushort)ipEndPoint.Port, server.RconPassword); _rconClients.Add(serverID, rconClient); rconClient.OnDisconnected += () => { Console.WriteLine($"RCON client for `{serverID}` has been disposed."); if (_rconClients.ContainsKey(serverID)) { _rconClients.Remove(serverID); } }; rconClient.OnLog += logMessage => { Console.WriteLine($"RCON: {logMessage}"); }; } return(_rconClients[serverID]); }
private async Task GetActivityStats() { if (string.IsNullOrWhiteSpace(_rconPassword) || string.IsNullOrWhiteSpace(_rconHost) || _rconPort <= 0) { return; } try { var status = await RCON.UDPSendCommand("status", _rconHost, _rconPassword, _rconPort); var serverStatus = new ServerStatus(status); var activity = new Game($"{serverStatus.Players.Count}", ActivityType.Playing, ActivityProperties.Play); await _discord.SetActivityAsync(activity); _currentActivity = activity; AsyncUtilities.DelayAction(TimeSpan.FromMinutes(1), async _ => { await GetActivityStats(); }); } catch (Exception e) { _logger.LogError(e, e.Message); } }
async void StartupTask() { while (rcon == null) { try { rcon = new RCON(host, port, password); } catch (System.AggregateException) { Console.WriteLine($"{Name} failed to connect"); } if (rcon != null) { rcon.OnDisconnected += onDisconnected; //rcon.SendCommandAsync("/RoutingReset").Wait(); ID = Int32.Parse(await rcon.SendCommandAsync("/RoutingGetID")); var json = new JavaScriptSerializer(); string mapstr = await rcon.SendCommandAsync($"/RoutingGetMap"); mapstr = mapstr.TrimEnd('\0', '\n'); var split = mapstr.IndexOf(':'); var len = UInt32.Parse(mapstr.Substring(0, split)); mapstr = mapstr.Substring(split + 1); if (mapstr.Length != len) { throw new Exception("Map Truncated"); } using (var ms = new System.IO.MemoryStream(Convert.FromBase64String(mapstr))) using (var gz = new System.IO.Compression.GZipStream(ms, System.IO.Compression.CompressionMode.Decompress)) using (var sr = new System.IO.StreamReader(gz)) { var mapjson = sr.ReadToEnd(); var map = json.Deserialize <IEnumerable <Dictionary <string, string> > >(mapjson); var siglist = map.Select(d => new SignalMap.SignalID { type = (string)d["type"], name = (string)d["name"] }); this.Map = new SignalMap(siglist); } rconAlive = true; ReceiveTask(); SendTask(); OnConnect?.Invoke(this); } else { // wait 30s Task.Delay(30000).Wait(); } } }
public async Task testBadAuthAsync() { //Warning ! This test can ban your ip in the server if sv_rcon_maxfailure is set to 0 //Use removeip to unban your ip (Default ban period is 60 min) rconClient.Dispose(); rconClient = new RCON(_ip, _port, "wrong PW"); await rconClient.ConnectAsync(); }
public async void PlayerNumUpdate() //玩家人数刷新 { RCON rcon = new RCON(IPAddress.Parse(IP_address), Port, Password); await rcon.ConnectAsync(); while (true) { var ret = await rcon.SendCommandAsync("list"); ret = ret.Replace("There are ", "").Replace("a max of ", "").Replace(" players online", ""); string[] PlayerInfo = Regex.Split(ret, " of ", RegexOptions.IgnoreCase); string[] PlayerList; try { PlayerList = Regex.Split(Regex.Split(PlayerInfo[1], ": ", RegexOptions.IgnoreCase)[1], ", ", RegexOptions.IgnoreCase); } catch { PlayerList = new string[] { }; } ushort PlayerNum = ushort.Parse(PlayerInfo[0]); if (PlayerList.Length == 0) { PlayerListBox.Items.Clear(); } List <string> PlayerListShowTemp = new List <string> { }; for (int i = 0; i < PlayerList.Length; ++i) //PlayerListBox.Items与PlayerList差异添加 { if (PlayerListBox.Items.IndexOf(PlayerList[i]) == -1) { PlayerListBox.Items.Add(PlayerList[i]); } } foreach (string i in PlayerListBox.Items) //避免foreach不可中途删除导致的错误 { PlayerListShowTemp.Add(i); } string[] PlayerListShow = PlayerListShowTemp.ToArray(); for (int i = 0; i < PlayerListShow.Length; ++i) //PlayerListBox.Items与PlayerList差异删除 { try { if (PlayerListBox.Items.IndexOf(PlayerList[i]) == -1) { PlayerListBox.Items.Remove(PlayerList[i]); } } catch { PlayerListBox.Items.Remove(PlayerListShow[i]);; } } PlayerNumLabel.Content = PlayerInfo[0] + " 个玩家在线"; await Task.Delay(1000); } }
public async Task TestRconGameMode() { var serverInfo = _settings.Left4DeadSettings.ServerInfo; using var rcon = new RCON(new IPEndPoint(IPAddress.Parse(serverInfo.Ip), serverInfo.Port), serverInfo.RconPassword); await rcon.ConnectAsync(); var gamemode = await rcon.SendCommandAsync <SmCvar>("sm_cvar mp_gamemode"); }
public async Task TestRconPrintInfo() { var serverInfo = _settings.Left4DeadSettings.ServerInfo; using var rcon = new RCON(new IPEndPoint(IPAddress.Parse(serverInfo.Ip), serverInfo.Port), serverInfo.RconPassword); await rcon.ConnectAsync(); var printInfo = await rcon.SendCommandAsync <PrintInfo>("sm_printinfo"); }
void onDisconnected() { // declare it dead... rconAlive = false; OnDisconnect?.Invoke(this); rcon = null; StartupTask(); }
public Settings() { Twitch = new Twitch(); Discord = new Discord(); Conan = new Conan(); RCON = new RCON(); Update = new Update(); General = new General(); }
static async Task Main(string[] args) { String ip; int port; String password; Console.WriteLine("Enter ip"); ip = Console.ReadLine(); Console.WriteLine("Enter port"); port = int.Parse(Console.ReadLine()); Console.WriteLine("Enter password"); password = Console.ReadLine(); var endpoint = new IPEndPoint( IPAddress.Parse(ip), port ); rcon = new RCON(endpoint, password, 0); await rcon.ConnectAsync(); bool connected = true; Console.WriteLine("Connected"); rcon.OnDisconnected += () => { Console.WriteLine("RCON Disconnected"); connected = false; }; while (connected) { String command = Console.ReadLine(); if (command == "conctest") { completed = 0; List <Thread> threadList = new List <Thread>(ThreadCount); for (int i = 0; i < ThreadCount; i++) { ThreadStart childref = new ThreadStart(ConcurrentTestAsync); Thread childThread = new Thread(childref); childThread.Start(); threadList.Add(childThread); } while (completed < ThreadCount) { await Task.Delay(1); } continue; } String response = await rcon.SendCommandAsync(command); Console.WriteLine(response); } }
public async Task testLongResponseAsync() { rconClient.Dispose(); rconClient = new RCON(_ip, _port, _password, 10000, true); //Enable multi packetsupport await rconClient.ConnectAsync(); string response = await rconClient.SendCommandAsync("cvarList"); Assert.IsTrue(response.EndsWith("total convars/concommands")); }
static async Task minecraft() { var serveraddress = IPAddress.Parse("127.0.0.1"); //IPアドレスとして扱うための変換 var serverpass = "******"; //RCONでログインするためのパスワード ushort port = 25575; //サーバのポート番号 string Player_Name = "Player_Name"; string TPCommand = "/tp " + Player_Name + " ~ ~ ~"; //プレイヤーの位置情報を得るためのコマンド //CoreRCONを使ってMinecraftへ接続 try { // Minecraft 接続環境(固定) var connection = new RCON(serveraddress, port, serverpass); var result = await connection.SendCommandAsync(TPCommand); //相対座標取得 string GetNum = Regex.Replace(result, @"[^0-9-,.]", ""); //座標数値のみ検索 string[] StrArray = GetNum.Split(','); //カンマで区切られた文字を部分的に取り出して、配列に保持 Console.WriteLine(result); //生のデータ double Position_x = double.Parse(StrArray[0]); //南北方向 北へ進むほど数値が小さくなる double Position_y = double.Parse(StrArray[1]); //高さ double Position_z = double.Parse(StrArray[2]); //東西方向 東へ進むほど数値が大きくなる Console.Write("Move x:"); double Input_x = double.Parse(Console.ReadLine()); //x座標入力 Console.Write("Move y:"); double Input_y = double.Parse(Console.ReadLine()); //y座標入力 Console.Write("Move z:"); double Input_z = double.Parse(Console.ReadLine()); //z座標入力 double Teleport_x = Position_x + Input_x; //移動後の座標x double Teleport_y = Position_y + Input_y; //移動後の座標y double Teleport_z = Position_z + Input_z; //移動後の座標z string Telepote_Command = "/tp " + Player_Name + " " + Teleport_x + " " + Teleport_y + " " + Teleport_z; result = await connection.SendCommandAsync(Telepote_Command); Console.WriteLine(Telepote_Command); //テレポート後のログ //完了コマンド(固定) Console.ForegroundColor = ConsoleColor.Green; //コンソール文字列に色付け Console.WriteLine("\nDone."); //ちょっとカッコつけて完了の表示 Console.ForegroundColor = ConsoleColor.White; //色を戻す } catch (Exception e) { Console.WriteLine(e); } Console.ReadKey(); }
private void setupRcon() { var ips = Dns.GetHostAddresses(_config.Hostname); var ip = ips.FirstOrDefault(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork); if (ip == null) { throw new Exception("Couldn't resolve rcon hostname to ip."); } _rcon = new RCON(ip, _config.Port, _config.Password); _rcon.OnDisconnected += onDisconnect; }
private async void ConnectButton_Click(object sender, RoutedEventArgs e) { string tmp_detail = ""; if (IP_Textbox.Text != "" && Port_Textbox.Text != "") { if (!IPAddress.TryParse(IP_Textbox.Text, out IPAddress IPCheck)) { tmp_detail += "Illegal IP address\n"; } if (int.Parse(Port_Textbox.Text) < 0 || int.Parse(Port_Textbox.Text) > 65536) { tmp_detail += "Wrong port"; } if (tmp_detail != "") { MessageExt.Instance.ShowDialog(tmp_detail, "Error"); } else { if (CheckConnect(IP_Textbox.Text, int.Parse(Port_Textbox.Text))) { IP_address = IP_Textbox.Text; Port = ushort.Parse(Port_Textbox.Text); Password = Password_Passwordbox.Password; var rcon = new RCON(IPAddress.Parse(IP_address), Port, Password); try { await rcon.ConnectAsync(); SaveConnectFile(IP_address, Port, Password); this.ShowInTaskbar = false; this.Visibility = Visibility.Hidden; Manage manage_window = new Manage(); manage_window.ShowDialog(); } catch (AuthenticationException) { MessageExt.Instance.ShowDialog("您的RCON密码验证失败", "错误"); } } else { MessageExt.Instance.ShowDialog("无法连接至服务器,请检查您输入的IP地址和RCON端口是否正确,且保证服务器开启了RCON", "错误"); } } } }
public RCONService(Settings settings) { Log.Information("Initializing RCON service..."); this._settings = settings; RCON rconSettings = _settings.RCON; rcon = RCONClient.INSTANCE; rcon.setupStream(rconSettings.RCONHost, rconSettings.RCONPort, rconSettings.RCONPassword); Log.Information("RCON service initialized!"); }
private void PlayerControlDEOP_Copy_Click(object sender, RoutedEventArgs e) { MessageExt.Instance.ShowYesNo("确认要将玩家" + PlayerControlNameLabel.Content + "的权限变更为成员吗?", "提示", new Action(() => { this.Dispatcher.Invoke((Action)async delegate() { RCON rcon = new RCON(IPAddress.Parse(IP_address), Port, Password); await rcon.ConnectAsync(); await rcon.SendCommandAsync("deop " + PlayerControlNameLabel.Content); await rcon.SendCommandAsync("tellraw @a [{\"text\":\"ASM\",\"color\":\"aqua\",\"bold\":true},{\"text\":\" >>> \",\"color\":\"green\",\"bold\":false},{\"text\":\"" + PlayerControlNameLabel.Content + "的权限等级已调整为成员\",\"color\":\"gold\"}]"); }); })); PlayerControlGrid.Visibility = Visibility.Hidden; }
public async Task <RCON> GetRconConnection() { SshClient client = await sshClient.Value; // TODO automagic restart if (!client.IsConnected) { throw new InvalidOperationException("Cannot get an RCON connection; SSH has been disconnected."); } RCON rcon = new RCON(IPAddress.Loopback, localRconPort, providerConfig.RconPassword); await rcon.ConnectAsync(); return(rcon); }
public IActionResult SendCommand([FromBody] Command cmd) { if (!ModelState.IsValid) { return(BadRequest()); } var admin = new ServerAdmin(HttpContext.User.Identity); var server = new Server(admin.ServerIp.ToString(), admin.ServerPort); var rcon = new RCON(server.Ip, server.Port, admin.Password); var result = rcon.SendCommandAsync(cmd.Cmd); return(Ok(result)); }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). _rcon?.Dispose(); _rcon = null; } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. disposedValue = true; } }
public List <string> Get() { var results = new List <string>(); try { var fc = new FabricClient(); var result = fc.ServiceManager.ResolveServicePartitionAsync(new Uri("fabric:/minecraft/DefaultMinecraftInstance")).Result; foreach (var endpoint in result.Endpoints) { var endpointObject = JsonConvert.DeserializeObject <Rootobject>(endpoint.Address); var hostArray = endpointObject.Endpoints.MinecraftRCONEndpoint.Split(':'); var rcon = new RCON(IPAddress.Parse(hostArray[0]), ushort.Parse(hostArray[1]), "cheesesteakjimmys"); // Send "status" var status = rcon.SendCommandAsync("list").Result; results.Add(status); } //try //{ // var ret = fc.ClusterManager.GetClusterManifestAsync().Result; // Console.WriteLine(ret.ToString()); //} //catch (Exception e) //{ // Console.WriteLine("Connect failed: {0}", e.Message); //} //FabricClient cl = new FabricClient("13.95.89.57:19000"); //var temp = cl.ServiceManager.GetServiceDescriptionAsync(new Uri("fabric:/MinecraftApplicationCluster/Guest")).Result; //temp.ToString(); //// Connect to a server //var rcon = new RCON(IPAddress.Parse("13.95.89.57"), 25575, "minecraft"); //// Send "status" //var status = rcon.SendCommandAsync("list").Result; //return status; } catch (Exception e) { throw e; } return(results); }