/// <summary> /// Connects to the mud server. Requires that the event handlers for required events be passed in here where they will /// be wired up. /// </summary> public async void Connect(EventHandler <string> lineReceived, EventHandler <string> dataReceived, EventHandler connectionClosed) { try { if (Telnet != null) { Telnet.Dispose(); Telnet = null; } Conveyor.EchoLog($"Connecting: {App.Settings.ProfileSettings.IpAddress}:{App.Settings.ProfileSettings.Port}", LogType.Information); var ctc = new CancellationTokenSource(); Telnet = new TelnetClient(App.Settings.ProfileSettings.IpAddress, App.Settings.ProfileSettings.Port, TimeSpan.FromSeconds(0), ctc.Token); Telnet.ConnectionClosed += connectionClosed; Telnet.LineReceived += lineReceived; Telnet.DataReceived += dataReceived; await Telnet.Connect(); } catch (Exception ex) { Telnet.Dispose(); Conveyor.EchoLog($"Connection Failed: {ex.Message}", LogType.Error); } }
public void ConnectClient() { TelClient = new TelnetClient(Host, Port, TimeSpan.Zero, CancelToken); TelClient.Connect().Wait(); TelClient.ConnectionClosed += OnConnectionClosed; TelClient.MessageReceived += OnMessageReceived; }
static void Main(string[] args) { //new connection var con = new TelnetClient(FromConfig.Server, 23, 30); try { if (!con.Login(FromConfig.Username, FromConfig.Password)) { throw new Exception("Failed to connect."); } Console.WriteLine("In"); con.SendAndWait("cd /", "$"); con.SendAndWait("ls -ltr", "$"); Console.WriteLine(con.SessionLog); con.Disconnect(); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(con.SessionLog); Console.WriteLine(ex.Message); } }
/// <summary> /// Translate structured data from the environment to pure text /// </summary> /// <param name="message">Message from the environment</param> /// <param name="telnetServer"></param> /// <param name="telnetClient"></param> public void Translate( IMessage message, TelnetServer telnetServer, TelnetClient telnetClient) { var graph = message.GetMessageAsType <CoreReadItemGraphResponse>(); void displayGraph(List <ItemGraph> graphItems, int level = 0) { if (graphItems != null && graphItems.Count > 0) { graphItems.ForEach(graphItem => { var line = "\r\n" + new string(' ', level * 2) + $"{AnsiColors.purpleB}{graphItem.Name} ({graphItem.Id}){AnsiColors.reset}"; telnetServer.SendMessageToClient(telnetClient, line); displayGraph(graphItem.Children, level + 1); }); } } displayGraph(new List <ItemGraph>() { graph.CoreReadItemGraphEvent.ItemGraph }); }
private async Task AsyncPingTelnetServer() { await TelnetClient.WriteLine("ping"); await Task.Delay(2000); await ReadAndSendEvent(true); }
public void ConnectTest() { TelnetClient client = new TelnetClient(); client.Connect("127.0.0.1", 5402); Assert.AreEqual(true, client.IsConnected()); }
/// <summary> /// TeamSpeak 3 ServerQuery client. See http://media.teamspeak.com/ts3_literature/TeamSpeak%203%20Server%20Query%20Manual.pdf. /// </summary> /// <param name="host">TeamSpeak 3 server hostname or IP address</param> /// <param name="port">ServerQuery port, you should probably set this to 10011. This is NOT the port your normal TS3 client connects to.</param> /// <param name="sendRate">Minimum time span between sends. This is a throttle to prevent flooding the server. Recommend 3+ seconds if you're not on the whitelist.</param> public ServerQueryClient(string host, int port, TimeSpan sendRate) { _commandQueue = new SemaphoreSlim(1); _cancellationSource = new CancellationTokenSource(); _telnetClient = new TelnetClient(host, port, sendRate, _cancellationSource.Token); _telnetClient.ConnectionClosed += HandleConnectionClosed; _telnetClient.MessageReceived += HandleMessageReceived; }
/// <summary> /// Translate structured data from the environment to pure text /// </summary> /// <param name="message">Message from the environment</param> /// <param name="telnetServer"></param> /// <param name="telnetClient"></param> public void Translate( IMessage message, TelnetServer telnetServer, TelnetClient telnetClient) { var tickEvent = message.GetMessageAsType <TickEvent>(); telnetServer.SendMessageToClient(telnetClient, "\r\n" + $"{AnsiColors.yellow}+{AnsiColors.reset}"); }
/// <summary> /// Translate structured data from the environment to pure text /// </summary> /// <param name="message">Message from the environment</param> /// <param name="telnetServer"></param> /// <param name="telnetClient"></param> public void Translate( IMessage message, TelnetServer telnetServer, TelnetClient telnetClient) { var response = message.GetMessageAsType <CoreReadItemJsonResponse>(); telnetServer.SendMessageToClient(telnetClient, $"\r\n{AnsiColors.purple}{response.CoreReadItemJsonEvent.ItemsJson.First().Id}{AnsiColors.reset}\r\n"); telnetServer.SendMessageToClient(telnetClient, $"{AnsiColors.purpleB}{response.CoreReadItemJsonEvent.ItemsJson.First().JSON}{AnsiColors.reset}\r\n"); }
/// <summary> /// Translate structured data from the environment to pure text /// </summary> /// <param name="message">Message from the environment</param> /// <param name="telnetServer"></param> /// <param name="telnetClient"></param> public void Translate( IMessage message, TelnetServer telnetServer, TelnetClient telnetClient) { var arrivalEvent = message.GetMessageAsType <CoreMoveItemEvent>(); var visible = arrivalEvent.Item.GetProperty <VisibleItemProperty>("Visible"); telnetServer.SendMessageToClient(telnetClient, "\r\n" + $"{AnsiColors.green}{visible?.Name} has moved{AnsiColors.reset}"); }
public bool IsUnjoinDomainSuccess() { TelnetClient telnetClient = new TelnetClient(config.ClientIP, config.TelnetPort, config.ClientAdminUsername, config.ClientAdminPwd); string response = string.Empty; StringBuilder command = new StringBuilder(); command.Append(config.ClientScriptPath + config.IsUnjoinDomainSuccessScript + " "); telnetClient.WriteCommand(command.ToString()); response = telnetClient.ReadResponse(); return(telnetClient.CheckResponse(response)); }
public bool UnjoinDomain() { //Samba does not support unjoin domain //or refer to nick's suggestion by deleting some ldb file on samba client TelnetClient telnetClient = new TelnetClient(config.ClientIP, config.TelnetPort, config.ClientAdminUsername, config.ClientAdminPwd); string response = string.Empty; StringBuilder command = new StringBuilder(); command.Append(config.ClientScriptPath + config.UnjoinDomainScript); telnetClient.WriteCommand(command.ToString()); response = telnetClient.ReadResponse(); return(telnetClient.CheckResponse(response)); }
private void Client_RemoteDisconnected(object sender, InternetFramework.Events.InternetConnectionEventArgs e) { if (grpConsole.InvokeRequired) { grpConsole.BeginInvoke(new MethodInvoker(delegate() { Client_RemoteDisconnected(sender, e); })); } else { txtConsole.Text += "Remote Disconnected."; SetConnected(false); Client = null; } }
/// <summary> /// Translate structured data from the environment to pure text /// </summary> /// <param name="message">Message from the environment</param> /// <param name="telnetServer"></param> /// <param name="telnetClient"></param> public void Translate( IMessage message, TelnetServer telnetServer, TelnetClient telnetClient) { var emoteEvent = message.GetMessageAsType <WorldEmoteEvent>(); var emote = ""; var itemName = emoteEvent.Origin.GetProperty <VisibleItemProperty>()?.Name ?? "** Something **"; emote = emoteEvent.EmoteType == WorldEmoteType.Smile ? $"{itemName} smiles happily" : emote; emote = emoteEvent.EmoteType == WorldEmoteType.Frown ? $"{itemName} frowns" : emote; telnetServer.SendMessageToClient(telnetClient, "\r\n" + $"{AnsiColors.whiteB}{emote}{AnsiColors.reset}"); }
public bool JoinDomainCreateAcctSAMR() { TelnetClient telnetClient = new TelnetClient(config.ClientIP, config.TelnetPort, config.ClientAdminUsername, config.ClientAdminPwd); string response = string.Empty; StringBuilder command = new StringBuilder(); command.Append(config.ClientScriptPath + config.JoinDomainCreateAcctSAMRScript + " "); command.Append(config.FullDomainName + " "); command.Append(config.DomainAdminUsername + " "); command.Append(config.DomainAdminPwd); telnetClient.WriteCommand(command.ToString()); response = telnetClient.ReadResponse(); return(telnetClient.CheckResponse(response)); }
public TelnetViewerViewModel(FileWriter fileWriter) { SendCommand = new DelegateCommand(OnSendCommand); ScrollHistoryCommand = new DelegateCommand <string>(OnScrollHistoryCommand); ClearUserInputCommand = new DelegateCommand(OnClearUserInputCommand); FileWriter = fileWriter; FileWriter.ExceptionOccurred += FileWriter_ExceptionOccurred; TelnetClient = new TelnetClient(); TelnetClient.ResponseReceived += TelnetClient_ResponseReceived; AlwaysScrollToEnd = true; commandHistory = new List <string>(); }
static void Main(string[] args) { TelnetClient tc = new TelnetClient(); //tc.ConnectionCheckingProc = null; Console.Write("Address: "); string a = "10.0.0.4"; // Console.ReadLine(); Console.Write("Port: "); string p = "23"; // Console.ReadLine(); Console.Write("Login: "******"admin"; // Console.ReadLine(); Console.Write("Passw: "); string pwd = "admin"; // Console.ReadLine(); bool res = tc.Connect( a, string.IsNullOrEmpty(p) ? 23 : int.Parse(p), string.IsNullOrEmpty(l) ? null : l, string.IsNullOrEmpty(pwd) ? null : pwd ); Console.WriteLine("Connection Result: {0}", res); string msg = ""; if (res) { while (msg != "exit") { Console.Write(tc.ReadToEnd() + " "); if (!tc.SendLine(msg = Console.ReadLine())) { Console.WriteLine(" *** error ***"); } } } Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); }
private async Task ReadAndSendEvent(bool FilterUnknownCommandOnPing = false) { ClientReadAsync = TelnetClient.ReadAsync(); await Task.WhenAll(ClientReadAsync); if (ClientReadAsync.Result != "") { if (FilterUnknownCommandOnPing) { string unknownCommandFilteredMessage = ClientReadAsync.Result.Replace("*** ERROR: unknown command 'ping'", ""); OnTelnetReceivedHandler?.Invoke(this, new OnTelnetReceivedEventArgs(unknownCommandFilteredMessage)); } else { OnTelnetReceivedHandler?.Invoke(this, new OnTelnetReceivedEventArgs(ClientReadAsync.Result)); } } //Console.Write(ClientReadAsync.Result); }
private async void btnConnect_Click(object sender, EventArgs e) { if (Client != null) { await Client.DisconnectAsync(); } else { using (Client = new TelnetClient(23, RFCProtocol.Telnet)) { Client.NewConnection += Client_NewConnection; Client.RemoteDisconnected += Client_RemoteDisconnected; Client.IncomingMessage += Client_IncomingMessage; txtConsole.Text = null; SetConnected(false); await Client.ConnectAsync(txtHost.Text); } } }
public ReturnObject Run(int planet) { Planet = planet; // Creates a telnet connection to NASA's Horizons database, on port 6775. telnetClient = new TelnetClient("horizons.jpl.nasa.gov", 6775, TimeSpan.FromSeconds(5), default(CancellationToken)); // Event handler methods are setup for the Telnet connection being closed and for a message being received. telnetClient.ConnectionClosed += HandleConnectionClosed; telnetClient.MessageReceived += HandleMessageReceived; // This starts the Telnet connection. telnetClient.Connect(); // Wait until completed. while (!Done) { continue; } return(RetVal); }
private void ConnectToServer(string ip, int port, TimeSpan delay) { if (_serverData.TelnetState != TelnetState.disconnected) { DisconnectFromServer(); } Logger.AddLog("Attempting to connect to " + ip + ": " + port); //create our new TelnetClient using the previous IPEndpoint _server = new TelnetClient(ip, port, delay, _serverCancellationToken); //setup our event handlers _server.ConnectionClosed += ConnectionClosedEvent; _server.MessageReceived += MessageReceivedEvent; //set the state to Connecting _serverData.TelnetState = TelnetState.connecting; _server.Connect(); }
/// <summary> /// Translate structured data from the environment to pure text /// </summary> /// <param name="message">Message from the environment</param> /// <param name="telnetServer"></param> /// <param name="telnetClient"></param> public void Translate( IMessage message, TelnetServer telnetServer, TelnetClient telnetClient) { var locationResponse = message.GetMessageAsType <WorldReadLocationSummaryResponse>(); telnetClient.ItemExits.Clear(); // Send location name and description telnetServer.SendMessageToClient(telnetClient, "\r\n\r\n" + $"{AnsiColors.greenB}{locationResponse.Item.GetProperty<VisibleItemProperty>().Name}{AnsiColors.reset}\r\n" + locationResponse.Item.GetProperty <VisibleItemProperty>().Description + "\r\n"); locationResponse.Adendums.ForEach(delegate(string adendum) { telnetServer.SendMessageToClient(telnetClient, " - " + adendum + "\r\n"); }); // Send location exits string exits = null; if (locationResponse.Exits.Count() > 0) { locationResponse.Exits.ForEach(ioExitUpdate => { telnetClient.ItemExits.Add(ioExitUpdate); var exit = ioExitUpdate.Item; var commands = ""; exit.GetProperty <CommandItemProperty>().Commands.ForEach(use => { commands += (commands == "") ? $"{use.Name}" : $"|{use.Name}"; }); exits = (exits == null) ? "" : $"{exits}, "; exits += $"{AnsiColors.purpleB}{exit.GetProperty<VisibleItemProperty>().Name} [{commands}]{AnsiColors.reset}"; }); } else { exits = "None"; } telnetServer.SendMessageToClient(telnetClient, $" - Exits: {exits}"); }
public void WriteLine(string line) { try { if (TelnetClient == null) { Console.WriteLine("*** telnetClient not initialized ***"); return; } else if (TelnetClient.IsConnected == false) { Console.WriteLine("*** telnetClient not connected ***"); return; } TelnetClient.WriteLine(line); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("*** Exception occured in WriteLine - wait 10 seconds before going on ***"); } }
public async void ReadTest() { string expected = "/instrumentation/heading-indicator/indicated-heading-deg = (double)\r\n/> "; string expected1 = "/controls/engines/current-engine/throttle = (double)\r\n/> "; TelnetClient client = new TelnetClient(); client.Connect("127.0.0.1", 5402); client.Send("get /instrumentation/heading-indicator/indicated-heading-deg \r\n"); string result = await client.Read(); client.Send("set /controls/engines/current-engine/throttle 1 \r\n"); string result1 = await client.Read(); int index = result.IndexOf('\''); int end = result.IndexOf('\'', index + 1); result = result.Remove(index, end - index + 1); index = result1.IndexOf('\''); end = result1.IndexOf('\'', index + 1); result1 = result1.Remove(index, end - index + 1); Assert.AreEqual(expected, result); Assert.AreEqual(expected1, result1); }
public override Server creack(String ip, int port, String username, String password, int timeOut) { TelnetClient tc = null; Server server = new Server(); try { tc = new TelnetClient(ip, port); String s = tc.Login(username, password, timeOut * 1000); String prompt = s.TrimEnd(); prompt = s.Substring(prompt.Length - 1, 1); server.banner = prompt; if (prompt != "$" && prompt != ">") { return(server); } if (tc.IsConnected) { server.isSuccess = true;; } } catch (Exception e) { throw e; } finally { if (tc != null) { tc.Dispose(); } } return(server); }
public string LocateDomainController() { TelnetClient telnetClient = new TelnetClient(config.ClientIP, config.TelnetPort, config.ClientAdminUsername, config.ClientAdminPwd); string response = string.Empty; StringBuilder command = new StringBuilder(); command.Append(config.ClientScriptPath + config.LocateDomainControllerScript + " "); command.Append(config.FullDomainName); telnetClient.WriteCommand(command.ToString()); response = telnetClient.ReadResponse(); string splitter = "\r\n"; int start = response.IndexOf(splitter, StringComparison.OrdinalIgnoreCase) + splitter.Length; int stop = response.LastIndexOf(splitter, StringComparison.OrdinalIgnoreCase); if (start >= stop) { return(null); } else { string result = response.Substring(start, stop - start); return(result); } }
public static void SendChat(TelnetClient telnet, string message) { TelnetException.CheckTelnetClient(telnet); telnet.WriteLine("say " + message); }
/// <summary> /// The query to send to the server chain. Likely wont work reliably with flags. /// </summary> /// <param name="QueryString">The Host or IP to query for</param> /// <returns>A collection of data from the server chain</returns> public QueryResponse Query(string QueryString) { QueryResponse queryResponse = new QueryResponse(); string whoisServer = "whois.arin.net"; string response = string.Empty; bool requery = false; do { if (!discoveredServers.Contains(whoisServer)) { discoveredServers.Add(whoisServer); } requery = false; TelnetClient client; try { if (whoisServer.Contains(":")) { client = new TelnetClient(whoisServer.To(":"), int.Parse(whoisServer.From(":"))); } else { client = new TelnetClient(whoisServer, 43); } response = client.Send(QueryString); } catch (Exception ex) { this.Error?.Invoke(ex); return(queryResponse); } queryResponse.ServerResponses.Add(new ServerResponse() { Response = response, Server = whoisServer, Request = QueryString }); if (response.Contains(REFERRAL_SERVER)) { requery = true; whoisServer = response.Split('\n').First(s => s.Contains(REFERRAL_SERVER)).From(": "); if (whoisServer.Contains("://")) { whoisServer = whoisServer.From("://"); } } } while (requery); WhoisResponse whoisResponse = new WhoisResponse(); foreach (string s in response.Split('\n')) { string toParse = s; if (toParse.StartsWith("#") || toParse.StartsWith("%") || string.IsNullOrWhiteSpace(toParse)) { continue; } Match m = Regex.Match(s, @"(.+)\s(.+)\s(\(.+\))\s([0-9\.]*)\s+-\s+([0-9\.]*)"); if (m.Success) { WhoisResponse thisResponse = new WhoisResponse(); thisResponse.OrgName = m.Groups[1].Value; thisResponse.NetName = m.Groups[2].Value; thisResponse.IPFrom = m.Groups[4].Value; thisResponse.IPTo = m.Groups[5].Value; queryResponse.WhoisResponses.Add(thisResponse); continue; } if (!toParse.Contains(":")) { continue; } if (toParse.StartsWith("network:")) { toParse = toParse.From(":"); } string key = toParse.To(":").Trim().ToLower(); string Value = toParse.From(":").Trim(); //wayport switch (key) { case "inetnum": case "netrange": case "ip-network-block": case "cidr": case "ip-network": if (Value.Contains("-")) { whoisResponse.IPFrom = Value.To("-").Trim(); whoisResponse.IPTo = Value.From("-").Trim(); } else if (Value.Contains("/")) { whoisResponse.CIDR = string.IsNullOrWhiteSpace(whoisResponse.Country) ? Value : $"{Value}, {whoisResponse.CIDR}"; } else { throw new Exception("Invalid network"); } break; case "netname": case "network-name": whoisResponse.NetName = Value; break; case "country": case "country-code": whoisResponse.Country = string.IsNullOrWhiteSpace(whoisResponse.Country) ? Value : whoisResponse.Country; break; case "org-name": case "orgname": case "organization;i": whoisResponse.OrgName = Value; break; } } //Make sure we have something to return if (!string.IsNullOrWhiteSpace(whoisResponse.CIDR) || !string.IsNullOrWhiteSpace(whoisResponse.IPFrom)) { queryResponse.WhoisResponses.Add(whoisResponse); } return(queryResponse); }