是否有可用于 C#(不是 ASP .NET)的良好、免费的 telnet 库?我在谷歌上找到了一些,但它们都有一个或另一个问题(不支持登录名/密码,不支持脚本模式)。
我假设 MS 仍然没有包含 telnet 库作为 .NET v3.5 的一部分,因为如果是的话我找不到它。不过,我会觉得错了。
我发现的最佳 C# Telnet Lib 称为 Minimalistic Telnet。非常容易理解、使用和修改。它适用于我需要配置的 Cisco 路由器。
这是我终于可以工作的代码
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");
}
}
我最终找到了MinimalistTelnet并将其改编为我的用途。由于我试图附加的唯一**设备,我最终需要能够大量修改代码。
** 在这种情况下,唯一可以有效地解释为脑死亡。
我目前正在评估两个可能感兴趣的 .NET (v2.0) C# Telnet 库:
希望这可以帮助。
问候,安迪。
另一个,它是一个较旧的项目,但共享完整的源代码:http ://telnetcsharp.codeplex.com/
我非常怀疑 telnet 库是否会成为 .Net BCL 的一部分,尽管您确实拥有几乎完整的套接字支持,因此模拟 telnet 客户端不会太难,Telnet 在其一般实现中是一种遗留且垂死的技术,其中存在通常位于一个漂亮的新现代外观后面。就 Unix/Linux 变体而言,您会发现开箱即用的 SSH 和启用 telnet 通常被认为是不好的做法。
您可以查看: http: //granados.sourceforge.net/ - .Net 的 SSH 库 http://www.tamirgal.com/home/dev.aspx?Item=SharpSsh
您仍然需要放置自己的包装器来处理事件,以便以脚本方式输入输入。