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

时间:2014-03-28 19:39:26

标签: c# asp.net ssh webforms

您好我创建了一个具有类似Putty的SSH终端的webapp。我使用SSH Library作为处理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;
    } 
}

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

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

        s.cmdInput = input.Text;

        output.Text = s.SSHConnect();
    }

任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:5)

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

SshCommand.Result属性(在下面的command.Result调用中使用)也封装了从OutputSteam中提取结果的逻辑,并使用this._session.ConnectionInfo.Encoding来读取OutputStream {1}}使用正确的编码。这应该有助于您收到的混乱线条。

以下是一个例子:

    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;
    }