Telnet Component Example |
---|
/// <summary> private Telnet telnet = new Telnet();
public TelnetCommander()
// set the option negotiation to false, so telnet servers require this to be true (we just have to test) telnet.OptionNegotiationEnabled = false; // set up event handler for when status changes telnet.OnConnectionStatusChanged += new Telnet.ConnectionStatusHandler(telnet_OnConnectionStatusChanged); // set up event for whenever we recieve anything telnet.OnReceive += new Telnet.ReceivedDataHandler(telnet_OnReceive); } public void Connect(string ipAddress, string password)
// enable welcome text, this means that we won't get a connected event, until the component, finds // the first string of text sent out by the server. telnet.WelcomeTextEnabled = true; // this is the text token we're search for in order to say that we successfully found the welcome text, // regex is supported, so we'll see if this system is password protected or not. telnet.WelcomeTextEndToken = "(Password:)|(\r\nOK\r\n)"; // connect to the server on port 23 telnet.Connect(ipAddress, 23); // if the server sends out it's welcome text and that text contains the string "password", we need to handle it.
// send the password
}string response = telnet.Send(password+"\r\n", new string[]{"(Password:)|(\r\nOK\r\n)"}, telnet.CommandTimeout); // if we still get a password prompt from the server, we go it wrong, so throw a bad password exception if(response.IndexOf("Password:")>=0) throw new Exception("Bad Password"); } public bool SendCommands(string data)
// make sure we're connected
}
if(telnet.ConnectionState != ConnectionState.Connected) throw new Exception("Not connected to device!");
// set the tokens that we will use to delimit each command, for a normal
if(command.Trim()=="")
}continue;
// send the command synchronously to the telnet server and wait for a response// note that we must terminate each command with a \n character as the component // sends EXACTLY what you give it. string response = telnet.Send(command + "\n"); // if we get an error response, from the telnet server, flag it. if(response.IndexOf("ERROR\r\n")>=0)
succeeded = false; return succeeded; public void Disconnect() { telnet.Disconnect();
}
public string GetState() { return telnet.ConnectionState.ToString();
}
private void telnet_OnConnectionStatusChanged(object o, ConnectionStatusEventArgs e) Console.WriteLine("Status: {0}", e.ConnectionState.ToString());
}
private void telnet_OnReceive(object o, ReceivedDataEventArgs e) Console.WriteLine("Rcd: {0}", e.ReceivedData);
}} |