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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1053468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 07:06:20  来源:igfitidea点击:

How can I open a telnet connection and run a few commands in C#

c#telnet

提问by Matt

IS this straightforward? Does any one have any good examples? All my google searches return items on how to make telnet clients in dotNet but this overkill for me. I'm trying to do this in C#.

这是直截了当的吗?有人有什么好的例子吗?我所有的谷歌搜索都返回有关如何在 dotNet 中创建 telnet 客户端的项目,但这对我来说太过分了。我试图在 C# 中做到这一点。

Thanks!

谢谢!

回答by Martin Vobr

For simple tasks (such as connecting to a specialized hardware device with telnet-like interface) connecting via socket and just sending and receiving text commands might be enough.

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

If you want to connect to real telnet server you might need to handle telnet escape sequences, face terminal emulation, handle interactive commands etc. Using some already tested code such as Minimalistic Telnet library from CodeProject(free) or some commercial Telnet/Terminal Emulator library (such as our Rebex Telnet) might save you some time.

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

Following code (taken from this url) shows how to use it:

以下代码(取自此 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();