如何在 C# 中打开 telnet 连接并运行一些命令
这简单吗? 有人有什么好的例子吗? 我所有的谷歌搜索都会返回有关如何在 dotNet 中创建 telnet 客户端的项目,但这对我来说太过分了。 我正在尝试用 C# 来做到这一点。
谢谢!
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#.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于简单的任务(例如连接到具有类似 telnet 接口的专用硬件设备),通过套接字连接并仅发送和接收文本命令可能就足够了。
如果您想连接到真正的 telnet 服务器,您可能需要处理 telnet 转义序列、面对终端仿真、处理交互式命令等。使用一些已经测试过的代码,例如 CodeProject 的简约 Telnet 库(免费)或一些商业 Telnet/终端仿真器库(例如我们的 Rebex Telnet)可能会节省您一些时间。
以下代码(取自此网址)显示了如何使用它:
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.
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.
Following code (taken from this url) shows how to use it:
C# 2.0 和 Telnet - 并不像听起来那么痛苦
http://geekswithblogs.net/bigpapa/archive/2007/10/08/C-2.0-and-Telnet---Not-As- Painful-As-It.aspx
或 此替代链接。
您可以查询 DNS.GetHostEntry 将计算机名称更改为
IPHostEntry 对象。
参数:AddressFamily.InterNetwork(IP 版本 4)、
SocketType.Stream(依赖于 InterNetwork 和 Tcp 参数),
ProtocolType.Tcp(可靠,双向连接)
这个:socket.Connect(端点); //是的,就是这么简单发送您的
使用 socket.Send(... 等等,我忘记了一些东西。你必须
首先对数据进行编码,以便它可以穿过电线。
Encoding.ASCII.GetBytes 将您拥有的好消息转换为
服务器到字节。 然后使用 socket.Send 将这些字节发送到它们的
方式。
使用 socket.Receive 不要忘记通过调用进行清理
套接字.关闭()
现在您可以分别使用stream.Write 和stream.Read 方法发送和接收数据。 顺便说一句,stream.Read 方法返回写入接收数组的字节数。
C# 2.0 and Telnet - Not As Painful As It Sounds
http://geekswithblogs.net/bigpapa/archive/2007/10/08/C-2.0-and-Telnet---Not-As-Painful-As-It.aspx
Or this alternative link.
You can query DNS.GetHostEntry to change a computer name to an
IPHostEntry object.
parameters: AddressFamily.InterNetwork (IP version 4),
SocketType.Stream (rides on InterNetwork and Tcp parameters),
ProtocolType.Tcp (reliable, two-way connection)
this: socket.Connect(endpoint); //yup, it's that simple Send your
data using socket.Send(... wait, I forgot something. You have to
encode the data first so it can fly across them wires.
Encoding.ASCII.GetBytes to convert the nice message you have for the
server into bytes. Then use socket.Send to send those bytes on their
way.
using socket.Receive Don't forget to clean up by calling
socket.Close()
Now you can send and receive data using the stream.Write and stream.Read methods, respectively. The stream.Read method returns the number of bytes written to your receiving array, by the way.