Due to the needs of a new project, I have been involved in the need to establish a telnet connection, so since we start investigating we do it from a Pocket PC, although the code I present is independent of the device, even Mono.

After reviewing several dotnettelnet type libraries, I opted for Minimalistic Telnet, basically because it was more adapted to my needs and it is much clearer what we intend to do at the learning level.

Easy, easy, easy recipe, using two simple functions we can work against our server

First we add the file Minimalistic Telnet to our project, and create the pair of functions, the first is merely to establish the connection, the necessary steps being to connect, and authenticate (txtDebug is a TextBox component to be able to see the results):

 

private void ConectToServer (string ip, string login, string password, int port, int timeout) {

try {

txtDebug.Text += “Connecting to " + ip + “: " + port + “… “;

//Connect to telnet server tc = new TelnetConnection(ip, port);

//We log in to the server txtDebug.Text + = tc.Login(login, password, timeout);

// We check the prompt symbol to ensure login, “$”, “#” or “>”, each server will give us the one it wants string prompt = s.TrimEnd(); txtDebug.Text += s; prompt = s.Substring(prompt.Length - 1, 1);

if (prompt != “$” && prompt != “>” && prompt != “#”)

//We can throw new Exception(“Connection failed”) or show it on the screen; txtDebug.Text += “Connection failed”;

if (tc.IsConnected) { txtDebug.Text = “Connected !!”; }

}

catch (Exception ex) { txtDebug.Text += “Connection error: " + ex.Message; }

}

 

Once connected, we can directly send the commands to be executed with another simple function:

 

private string SendTelnetData(string prompt) {

// If connected… if (tc.IsConnected) {

// we send the command tc.WriteLine(prompt); prompt += tc.Read();

}

else { lblStatus.Text = “Offline”; }

return prompt;

}

With calls to these two functions we have everything solved, for example:

ConectToServer(“192.168.1.1”, “user”, “password”, 23, 100); SendTelnetData(“command1”); SendTelnetData(“command2”);

Let’s not forget that to disconnect we would only need to send the instruction:

SendTelnetData(“exit”);

Who’s up to making the SSH version?