Skip to main content
 首页 » 编程设计

c#之使用 ASP.NET 的 Web 应用程序中的 SSH 终端

2024年02月01日25xxx_UU

你好,我创建了一个 webapp,它有一个类似于 Putty 的 SSH 终端。我正在使用 SSH Library作为处理 ssh 流的一种方式。但是有一个问题。我可以登录到 Cisco 2950 并输入命令,但结果却乱七八糟地排成一行。 此外,当我尝试“conf t”时,它会进入配置终端,但随后您什么也做不了,并且会弹出“Line has invalid autocommand”?

这是我目前的代码:

这是与库交互的 SSH.cs。

public class SSH 
{ 
    public string cmdInput { get; set; } 
 
    public string SSHConnect() 
    { 
        var PasswordConnection = new PasswordAuthenticationMethod("username", "password"); 
        var KeyboardInteractive = new KeyboardInteractiveAuthenticationMethod("username"); 
        // jmccarthy is the username 
        var connectionInfo = new ConnectionInfo("10.56.1.2", 22, "username", PasswordConnection, KeyboardInteractive); 
        var ssh = new SshClient(connectionInfo); 
 
        ssh.Connect(); 
        var cmd = ssh.CreateCommand(cmdInput); 
        var asynch = cmd.BeginExecute(delegate(IAsyncResult ar) 
        { 
            //Console.WriteLine("Finished."); 
        }, null); 
 
        var reader = new StreamReader(cmd.OutputStream); 
        var myData = ""; 
 
        while (!asynch.IsCompleted) 
        { 
            var result = reader.ReadToEnd(); 
            if (string.IsNullOrEmpty(result)) 
                continue; 
            myData = result; 
        } 
 
        cmd.EndExecute(asynch); 
        return myData; 
    }  
} 

这是在网页上显示代码的 .aspx.cs 中的代码。

protected void CMD(object sender, EventArgs e) 
    { 
        SSH s = new SSH(); 
 
        s.cmdInput = input.Text; 
 
        output.Text = s.SSHConnect(); 
    } 

如有任何帮助,我们将不胜感激。

请您参考如下方法:

通过查看 SSH.NET 库代码中的测试用例,您可以使用 RunCommand 方法代替 CreateCommand,后者将同步处理命令。我还为 SshClient ssh 对象添加了一个 using block ,因为它实现了 iDisposable。记得同时调用 Disconnect,这样您就不会被打开的连接卡住。

还有 SshCommand.Result 属性(在下面的 command.Result 调用中使用)封装了从 OutputSteam 中提取结果的逻辑>,并使用 this._session.ConnectionInfo.Encoding 使用正确的编码读取 OutputStream。这应该有助于解决您收到的困惑线路。

这是一个例子:

    public string SSHConnect() { 
        var PasswordConnection = new PasswordAuthenticationMethod("username", "password"); 
        var KeyboardInteractive = new KeyboardInteractiveAuthenticationMethod("username"); 
        string myData = null; 
 
        var connectionInfo = new ConnectionInfo("10.56.1.2", 22, "username", PasswordConnection, KeyboardInteractive); 
 
        using (SshClient ssh = new SshClient(connectionInfo)){ 
            ssh.Connect(); 
            var command = ssh.RunCommand(cmdInput); 
            myData = command.Result; 
            ssh.Disconnect(); 
        } 
 
        return myData; 
    }