Search code examples
c#telnet

send password as command via Telnet in C#


I want to connect to a cisco switch via telnet in c#.I want to send commands in cmd with c# and when it asks for password I want to enter it with my program. But my problem is that I can’t send password when it is connected to telnet.And when I used StreamWriter it throws an exception.
Here is my code:

class Program
{
    static void Main(string[] args)
    {
        string data = "";  
        StreamReader reader = new StreamReader(@"C:\Windows\System32");  
        StreamWriter writer = new StreamWriter(@"C:\Windows\System32");  
        IPAddress address = IPAddress.Parse("172.16.0.110");  
        IPEndPoint ipe = new IPEndPoint(address, 23);  
        Socket telnetSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);  
        telnetSocket.Connect(ipe);  
        NetworkStream NsStream = new NetworkStream(telnetSocket, true);  
        if (telnetSocket.Connected)  
        {  
            NsStream = new NetworkStream(telnetSocket, true);  
            reader = new StreamReader(NsStream);  
        }  

        while (!reader.EndOfStream)  
        {  
            data = reader.ReadLine();  
            if (data.Contains("Password:"))  
            {  
                //I want to enter password in cmd here  
            }  
        }  
        reader.Close();  
        if (NsStream == null)  
            NsStream.Close();  
    }
}

Solution

  • If you use a lib like SSH.NET you get all these problems solved for you and no need to reinvent the wheel again!