使用ASP.NET的webapp中的SSH终端

Val*_*gul 1 c# asp.net ssh webforms

您好我创建了一个具有类似Putty的SSH终端的webapp.我使用SSH库作为处理ssh流的方法.但是有一个问题.我可以登录到Cisco 2950并输入命令,但它会混乱并且在一行中.此外,当我尝试"conf t"时,它进入配置终端,但是你不能做任何事情,这会弹出"Line有无效的自动命令"?".

这是我到目前为止的代码:

这是与库交互的SSH.c.

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;
    } 
}
Run Code Online (Sandbox Code Playgroud)

这是.aspx.cs中的代码,用于显示网页上的代码.

protected void CMD(object sender, EventArgs e)
    {
        SSH s = new SSH();

        s.cmdInput = input.Text;

        output.Text = s.SSHConnect();
    }
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.

Bat*_*ech 5

通过查看SSH.NET库代码中的测试用例,您可以使用该RunCommand方法代替CreateCommand,该方法将同步处理该命令.我还为该SshClient ssh对象添加了一个using块,因为它实现了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;
    }
Run Code Online (Sandbox Code Playgroud)