在 C# 中通过 Telnet 发送和接收命令

Posted

技术标签:

【中文标题】在 C# 中通过 Telnet 发送和接收命令【英文标题】:Send and Receive commands via Telnet in C# 【发布时间】:2014-09-26 18:33:21 【问题描述】:

我是 Telnet 新手,我需要用 WPF (C#) 编写一个小程序,通过 telnet 向设备发送和接收命令。

开头是:

    发送命令“telnet 192.168.0.50”(为了连接到设备) 然后发送“用户”和“密码” 然后开始向设备发送和接收数据,所有通信需要显示在 WPF 日志屏幕上。

我在 Google 上搜索了有关如何操作的信息,但没有找到对我有帮助的信息。

我在这里问是因为我很无助,我需要一些方向才能从某个地方开始......我非常感谢你的帮助。

谢谢。

【问题讨论】:

我搜索了“c# issue telnet command”,找到了数百篇文章。 检查这个问题:***.com/questions/390188/c-sharp-telnet-library Telnet是简单的SocketClient和SocketServer,默认在23端口。 【参考方案1】:

我有一个 GitHub 项目 https://github.com/9swampy/Telnet/,也作为 NuGet dll https://www.nuget.org/packages/Telnet 发布,这将允许您:

using (Client client = new Client(server.IPAddress.ToString(), server.Port, new System.Threading.CancellationToken()))

  await client.TryLoginAsync("username", "password", TimeoutMs);
  client.WriteLine("whatever command you want to send");
  string response = await client.TerminatedReadAsync(">", TimeSpan.FromMilliseconds(TimeoutMs));

这应该可以让您在应用程序中实现您想要的,如果您想查看使这一切正常运行的代码,您可以查看 GitHub。

【讨论】:

【参考方案2】:

大致(在 VB 中,但应该很容易转换为 c#)。您只需添加位即可将用户名和密码写入流

Dim Data As String
Dim reader As StreamReader = Nothing
Dim NsStream As NetworkStream = Nothing
dim address as IPAddress = IPAddress.Parse("192.168.0.50")
Dim ipe As New IPEndPoint(address, port)
Dim telnetSocket As New Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp)

telnetSocket.Connect(ipe)

 If (telnetSocket.Connected) Then
     Try
    
         'if is necessary to send a command
         'telnetSocket.Send(Encoding.ASCII.GetBytes("Command to execute"))

         NsStream = New NetworkStream(telnetSocket, True)
         reader = New StreamReader(NsStream)

         Do While (Not reader.EndOfStream)

             ' Read the line of data
              Data = reader.ReadLine()
             'Do whatever with data
         Loop
    
    Catch ex As Exception
           Msgbox(ex.message)
    Finally
            Try
                If reader IsNot Nothing Then
                    reader.Close()
                End If
            Catch ex As Exception
            End Try
            Try
                If NsStream IsNot Nothing Then
                    NsStream.Close()
                End If
            Catch ex As Exception
            End Try
        End Try

end if

【讨论】:

以上是关于在 C# 中通过 Telnet 发送和接收命令的主要内容,如果未能解决你的问题,请参考以下文章

在 C# 中通过 POST 发送 JSON 并接收返回的 JSON?

捕获文件在 C# 中通过蓝牙发送

C# - 向 Telnet 服务器发送命令(纯文本)

我将如何在 Javascript 中通过 WebSocket 发送和接收数据包

在 C 程序中使用 telnet

如何在 Chrome 中通过 nativeMessaging 发送/接收短信?