Search code examples
c#telnet

Telnet C# how to login and send commands to the terminal


I have the following code and using this nuget package for telnet https://www.nuget.org/packages/Telnet

using PrimS.Telnet;

public class Program
{
    public async static Task Main()
    {
       using var client = new Client(new TcpByteStream("some endpoint", 23), new CancellationToken());
    
       // This flag returns false      
       var isLoginSuccess = await client.TryLoginAsync("user", "pass", 5000);

       await client.WriteAsync("ls\n");

       // Data does show everything in the directory even though isLoginSuccess is false
       string data = await client.ReadAsync();
    }
}

Solution

  • Since we don't know what server you're connecting to and the question lacks traffic captures, we can't debug this for you, but we can make some educated guesses.

    According to the documentation of the Telnet library you used, it's possible your server uses a non-standard terminator:

    Try login uses a 'terminator' (the character after which you start writing commands) to detect if the login was successful (default is >). The terminator character is found after login and you can begin entering commands, for example, > configure - '>' is the terminator. If the terminator/linestarter is different to '>', you will need to specify it as a extra parameter. client.TryLoginAsync(<username>, <password>, <Timout ms>, <terminator>, <lineFeed default='\n'>)

    Furthermore, they suggest this solution for non-standard servers:

    Please note it is just a wrapper for Read and Write calls to cover the most common scenario. If it doesn't work, roll your own TerminatedReads and Writes to service your specific UseCase.

    However, since you managed to run commands regardless of the login success, it's possible that your telnet server doesn't require logging-in at all. In that case, just skip the login altogether!