Another option you have is to use a
TcpClient and
NetworkStream to communicate with a telnet server. Here's a small example of doing this (It's setup in a console application for this example).
We got 2 methods (other than Main), one for writing data to the steam and one for reading the response received back:
WriteIn - private static void WriteIn(string input)
-
{
-
if (stream.CanWrite)
-
{
-
writeBuffer = System.Text.Encoding.ASCII.GetBytes(input);
-
stream.Write(writeBuffer, 0, writeBuffer.Length);
-
}
-
}
ReadOut - private static string ReadOut()
-
{
-
string output = null;
-
-
if (stream.CanRead)
-
{
-
readBuffer = new byte[tcpClient.ReceiveBufferSize];
-
stream.Read(readBuffer, 0, tcpClient.ReceiveBufferSize);
-
-
output = System.Text.Encoding.ASCII.GetString(readBuffer).Trim();
-
}
-
-
return output;
-
}
For this example we have 4 variables that are global to our application
- private static NetworkStream stream;
-
private static TcpClient tcpClient;
-
private static byte[] writeBuffer;
-
private static byte[] readBuffer;
And our Main method does all the communicating with the telnet server:
Main - static void Main(string[] args)
-
{
-
try
-
{
-
using (tcpClient = new TcpClient())
-
{
-
Console.WriteLine("Please enter the host IP:");
-
string host = Console.ReadLine();
-
-
Console.WriteLine("Please provide the port to connect on:");
-
int port = int.Parse(Console.ReadLine());
-
-
tcpClient.Connect(host, port);
-
-
using (stream = tcpClient.GetStream())
-
{
-
Console.WriteLine(ReadOut());
-
-
Console.WriteLine("Enter your username:");
-
WriteIn(Console.ReadLine());
-
-
Console.WriteLine(ReadOut());
-
-
Console.WriteLine("Enter your password:");
-
WriteIn(Console.ReadLine());
-
-
Console.WriteLine(ReadOut());
-
-
-
}
-
}
-
//keep it open
-
Console.ReadLine();
-
}
-
catch (SocketException ex)
-
{
-
Console.WriteLine("Socket Error: {0}", ex.Message);
-
}
-
catch (Exception ex)
-
{
-
Console.WriteLine("ERROR: {0}", ex.Message);
-
}
-
}
Once you enter your username & password then you can issue your commands with
WriteIn and use
ReadOut to read the response.
Hope this helps and gives you another option