【问题标题】:send password as command via Telnet in C#在 C# 中通过 Telnet 作为命令发送密码
【发布时间】:2017-07-18 01:17:23
【问题描述】:

我想在 c# 中通过 telnet 连接到 cisco 交换机。我想用 c# 在 cmd 中发送命令,当它要求输入密码时,我想用我的程序输入它。但是我的问题是连接到telnet时无法发送密码。当我使用StreamWriter时它会抛出异常。
这是我的代码:

class Program
{
    static void Main(string[] args)
    {
        string data = "";  
        StreamReader reader = new StreamReader(@"C:\Windows\System32");  
        StreamWriter writer = new StreamWriter(@"C:\Windows\System32");  
        IPAddress address = IPAddress.Parse("172.16.0.110");  
        IPEndPoint ipe = new IPEndPoint(address, 23);  
        Socket telnetSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp);  
        telnetSocket.Connect(ipe);  
        NetworkStream NsStream = new NetworkStream(telnetSocket, true);  
        if (telnetSocket.Connected)  
        {  
            NsStream = new NetworkStream(telnetSocket, true);  
            reader = new StreamReader(NsStream);  
        }  

        while (!reader.EndOfStream)  
        {  
            data = reader.ReadLine();  
            if (data.Contains("Password:"))  
            {  
                //I want to enter password in cmd here  
            }  
        }  
        reader.Close();  
        if (NsStream == null)  
            NsStream.Close();  
    }
}

【问题讨论】:

标签: c# telnet


【解决方案1】:

您将需要使用 Telnet。 Telnet rfcs 会给你一个想法,你正在处理什么。 https://www.rfc-editor.org/rfc/rfc854

如果您想手动完成此操作,一些建议可能会有所帮助。或者说明为什么使用 telnet 库可能是个好主意。

  • TcpClient 会稍微减少你的工作量。至少它会为你创建 NetworkStream。

  • 您可能可以忽略大部分协议细节,但不能忽略初始选项协商。您最初可能希望处理原始 NetworkStream,因为 telnet 会话以“选项”协商开始。快速搜索 telnet 选项协商会出现这种情况:How to deal with the telnet negotiation

上面使用reader/writer有两个问题:

  • 默认情况下它们将使用 UTF8 编码,因此 telnet 选项协商数据(不是 7 位 ASCII)可能会发生变异。
  • Readline() 可能无论如何都会挂起,因为它会读取 telnet 选项,这是服务器发送的第一件事,但随后会继续尝试读取直到行的第一个结尾......这永远不会到达,因为服务器正在等待对其发送的选项的响应。即您需要完成 telnet 选项协商。

【讨论】:

    【解决方案2】:

    如果您使用像 SSH.NET 这样的库,您可以为您解决所有这些问题,无需重新发明轮子!

    【讨论】:

      猜你喜欢
      • 2014-09-26
      • 2014-11-02
      • 1970-01-01
      • 2015-02-19
      • 2018-12-13
      • 2020-09-01
      • 2011-12-06
      • 2015-03-05
      • 1970-01-01
      相关资源
      最近更新 更多