C#Telnet库

sal*_*cer 51 .net c# telnet

是否有一个好的,免费的telnet库可用于C#(不是ASP .NET)?我在谷歌上发现了一些,但它们都有一个或另一个问题(不支持登录/密码,不支持脚本模式).

我假设MS仍然没有包含一个telnet库作为.NET v3.5的一部分,因为我找不到它.尽管如此,我还是会错的.

小智 48

最好的C#Telnet Lib我发现它被称为Minimalistic Telnet.很容易理解,使用和修改.它适用于我需要配置的Cisco路由器.

http://www.codeproject.com/KB/IP/MinimalisticTelnet.aspx

  • 到目前为止,这也是我发现的最佳工作示例.我的派生/更新工作在GitHub上,如果有兴趣的话,可以在NuGet上发布.https://github.com/9swampy/Telnet (3认同)
  • 感谢@ 9swampy在GitHub上提供更新版本.此评论应作为答案的更新包含在内,因为它很难找到,并且您的版本比原始版本有了很大改进. (2认同)

小智 8

这是我的代码终于工作了

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;

class TelnetTest
{

    static void Main(string[] args)
    {
        TelnetTest tt = new TelnetTest();

    tt.tcpClient = new TcpClient("myserver", 23);
    tt.ns = tt.tcpClient.GetStream();

    tt.connectHost("admin", "admin");
    tt.sendCommand();

    tt.tcpClient.Close();
}

public void connectHost(string user, string passwd) {
    bool i = true;
    while (i)
    {
        Console.WriteLine("Connecting.....");
        Byte[] output = new Byte[1024];
        String responseoutput = String.Empty;
        Byte[] cmd = System.Text.Encoding.ASCII.GetBytes("\n");
        ns.Write(cmd, 0, cmd.Length);

        Thread.Sleep(1000);
        Int32 bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.WriteLine("Responseoutput: " + responseoutput);
        Regex objToMatch = new Regex("login:");
        if (objToMatch.IsMatch(responseoutput)) {
           cmd = System.Text.Encoding.ASCII.GetBytes(user + "\r");
           ns.Write(cmd, 0, cmd.Length);
        }

        Thread.Sleep(1000);
        bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.Write(responseoutput);
        objToMatch = new Regex("Password");
        if (objToMatch.IsMatch(responseoutput))
        {
            cmd = System.Text.Encoding.ASCII.GetBytes(passwd + "\r");
            ns.Write(cmd, 0, cmd.Length);
        }

        Thread.Sleep(1000);
        bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.Write("Responseoutput: " + responseoutput);

        objToMatch = new Regex("#");
        if (objToMatch.IsMatch(responseoutput))
        {
            i = false;
        }

    }

    Console.WriteLine("Just works");
}
}
Run Code Online (Sandbox Code Playgroud)

  • ns 变量指的是什么? (4认同)
  • 好的。粗糙且准备就绪并且大部分工作正常,但我建议在 .Read() 之前检查是否有 ns.DataAvailable 因为可能没有响应,并且您将永远阻塞;还要将 .Read() 放在一个循环中以继续读取,因为您可能没有一次性读取所有数据。 (2认同)
  • `tcpClient` 字段在哪里? (2认同)