如何在C#中打开telnet连接并运行一些命令

这是直截了当的吗? 有人有任何好的例子吗? 我所有的谷歌搜索都返回了关于如何在dotNet上制作telnet客户端的项目,但这对我来说太过分了。 我想用C#做这个。

谢谢!

对于简单的任务(例如连接到具有类似telnet接口的专用硬件设备),通过套接字连接并且仅发送和接收文本命令就足够了。

如果你想连接到真正的telnet服务器,你可能需要处理telnet转义序列,面对终端仿真,处理交互式命令等。使用一些已经测试过的代码,如CodeProject的Minimalistic Telnet库 (免费)或一些商业Telnet /终端仿真器库(比如我们的Rebex Telnet )可能会为您节省一些时间。

以下代码(取自此url )显示了如何使用它:

// create the client Telnet client = new Telnet("servername"); // start the Shell to send commands and read responses Shell shell = client.StartShell(); // set the prompt of the remote server's shell first shell.Prompt = "servername# "; // read a welcome message string welcome = shell.ReadAll(); // display welcome message Console.WriteLine(welcome); // send the 'df' command shell.SendCommand("df"); // read all response, effectively waiting for the command to end string response = shell.ReadAll(); // display the output Console.WriteLine("Disk usage info:"); Console.WriteLine(response); // close the shell shell.Close();