是否有一个好的,免费的telnet库可用于C#(不是ASP .NET)?我在谷歌上发现了一些,但它们都有一个或另一个问题(不支持登录/密码,不支持脚本模式).
我假设MS仍然没有包含一个telnet库作为.NET v3.5的一部分,因为我找不到它.尽管如此,我还是会错的.
最好的C#Telnet Lib我发现它被称为Minimalistic Telnet.很容易理解,使用和修改.它适用于我需要配置的Cisco路由器.
http://www.codeproject.com/KB/IP/MinimalisticTelnet.aspx
这是我的代码终于工作了
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"); } }