3

我有一个 C# 应用程序需要通过 SSH 在硬件上运行某些命令。应用程序SSH.Net用于建立连接、发送命令和读取结果。如果我使用 OpenSSH 连接到我的本地机器,我就有这个工作。最后,我想更进一步,设置我自己的 SSH 服务器,这样我就可以一次模拟多个硬件设备(需要模拟有 50 多个设备可以通过 SSH 连接)。

为此,我使用 nodejs 和ssh2包设置了一个简单的 SSH 服务器。到目前为止,我已经连接了客户端,通过了身份验证(现在接受所有连接),并且我可以看到session正在创建一个对象。虽然我碰壁的地方是执行客户端发送的命令。我注意到在对象上ssh2有一个事件,但这似乎永远不会触发(不管我在's中放了什么)。execsessionSSH.NetShellStream

启动连接的 C# 客户端代码如下(command已经定义了要执行的命令字符串):

using(SshClient client = new SshClient(hostname, port, username, password))
{
    try
    {
        client.ErrorOccurred += Client_ErrorOccurred;
        client.Connect();

        ShellStream shellStream = client.CreateShellStream("xterm", Columns, Rows, Width, Height, BufferSize, terminalModes);

        var initialPrompt = await ReadDataAsync(shellStream);

        // The command I write to the stream will get executed on OpenSSH
        // but not on the nodejs SSH server
        shellStream.WriteLine(command);
        var output = await ReadDataAsync(shellStream);
        var results = $"Command: {command} \nResult: {output}";

        client.Disconnect();

        Console.WriteLine($"Prompt: {initialPrompt} \n{results}\n");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Exception during SSH connection: {ex.ToString()}");
    }
}

设置 ssh2 服务器的 nodejs 服务器代码如下:

new ssh2.Server({
  hostKeys: [fs.readFileSync('host.key')]
}, function(client) {
  console.log('Client connected!');

  client.on('authentication', function(ctx) {
    ctx.accept();
  }).on('ready', function() {
    console.log('Client authenticated!');

    client.on('session', function(accept, reject) {
      var session = accept();

      // Code gets here but never triggers the exec
      session.once('exec', function(accept, reject, info) {
        console.log('Client wants to execute: ' + inspect(info.command));
        var stream = accept();
        stream.write('returned result\n');
        stream.exit(0);
        stream.end();
      });
    });
  }).on('end', function() {
    console.log('Client disconnected');
  });
}).listen(port, '127.0.0.1', function() {
  console.log('Listening on port ' + this.address().port);
});

我见过各种ssh2调用client.exec函数的客户端示例,但我假设我的客户端没有使用ssh2节点包并不重要。有什么我在这里想念的吗?

4

1 回答 1

1

"exec" Node.js 服务器会话事件用于"non-interactive (exec) command execution"。它们很可能是指 SSH “exec” 通道(用于“非交互式命令执行”)。

要在 SSH.NET 中使用“exec”SSH 通道执行命令,请使用SshClient.RunCommand.


相反,SshClient.CreateShellStream使用 SSH“shell”通道,该通道旨在实现交互式 shell 会话。

为此,您需要处理“shell” Node.js 服务器会话事件

于 2018-11-15T18:09:25.183 回答