Javascript 连接到远程 SSH 服务器(通过 Node.js/html5 控制台)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38689707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:43:28  来源:igfitidea点击:

Connecting to remote SSH server (via Node.js/html5 console)

javascriptnode.jswindowshtmlssh

提问by Ethan

I have been scouring the face of the web looking to answer a question which I had thought would be simple. My goal is straight forward. I want to build out a simple web-based SSH client using Node.js module(s). I have found several options if I want to connect to the node server itself, but can't seem to find any examples of connecting to a REMOTE server.

我一直在网上搜索,希望回答一个我认为很简单的问题。我的目标很明确。我想使用 Node.js 模块构建一个简单的基于 Web 的 SSH 客户端。如果我想连接到节点服务器本身,我已经找到了几个选项,但似乎找不到任何连接到远程服务器的示例。

Essentially the outcome I am looking for is a workflow like this : Connect to webserver -> Click on a server name in a list of servers -> Enter SSH session to the server I clicked on

基本上,我正在寻找的结果是这样的工作流程:连接到网络服务器 -> 单击服务器列表中的服务器名称 -> 输入到我单击的服务器的 SSH 会话

The only thing I have found that's even remotely close to what I am looking for is guacamole. I do not want to use guacamole, however, as I want this application to be OS independent. Currently I am building it on a windows 10 platform, and will port it over to fedora when I am done.

我发现的唯一与我正在寻找的东西非常接近的东西是guacamole。但是,我不想使用鳄梨酱,因为我希望此应用程序独立于操作系统。目前我正在 Windows 10 平台上构建它,并在完成后将其移植到 Fedora。

I found this tutorial for creating an SSH terminal. However, all this does is creates (or attempts to create) an SSH connection to the local system.

我找到了创建 SSH 终端的教程。然而,这一切只是创建(或尝试创建)到本地系统的 SSH 连接。

Another options that looked absolutely fantastic was tty.js. Alas, the bottom-line is the same as the above tutorial. The module only allows you to connect to the node.js server, NOT to remote servers.

另一个看起来非常棒的选项是tty.js。唉,底线与上述教程相同。该模块只允许您连接到 node.js 服务器,而不是远程服务器。

Anyone have information on a possible path to this goal?

任何人都有关于实现这一目标的可能途径的信息?

回答by mscdex

This is easily doable with modules like ssh2, xterm, and socket.io.

这是用相似的模块容易可行的ssh2xtermsocket.io

Here's an example:

下面是一个例子:

  1. npm install ssh2 xterm socket.io
  2. Create index.html:
  1. npm install ssh2 xterm socket.io
  2. 创建index.html
<html>
  <head>
    <title>SSH Terminal</title>
    <link rel="stylesheet" href="/src/xterm.css" />
    <script src="/src/xterm.js"></script>
    <script src="/addons/fit/fit.js"></script>
    <script src="/socket.io/socket.io.js"></script>
    <script>
      window.addEventListener('load', function() {
        var terminalContainer = document.getElementById('terminal-container');
        var term = new Terminal({ cursorBlink: true });
        term.open(terminalContainer);
        term.fit();

        var socket = io.connect();
        socket.on('connect', function() {
          term.write('\r\n*** Connected to backend***\r\n');

          // Browser -> Backend
          term.on('data', function(data) {
            socket.emit('data', data);
          });

          // Backend -> Browser
          socket.on('data', function(data) {
            term.write(data);
          });

          socket.on('disconnect', function() {
            term.write('\r\n*** Disconnected from backend***\r\n');
          });
        });
      }, false);
    </script>
    <style>
      body {
        font-family: helvetica, sans-serif, arial;
        font-size: 1em;
        color: #111;
      }
      h1 {
        text-align: center;
      }
      #terminal-container {
        width: 960px;
        height: 600px;
        margin: 0 auto;
        padding: 2px;
      }
      #terminal-container .terminal {
        background-color: #111;
        color: #fafafa;
        padding: 2px;
      }
      #terminal-container .terminal:focus .terminal-cursor {
        background-color: #fafafa;
      }
    </style>
  </head>
  <body>
    <div id="terminal-container"></div>
  </body>
</html>
  1. Create server.js:
  1. 创建server.js
var fs = require('fs');
var path = require('path');
var server = require('http').createServer(onRequest);

var io = require('socket.io')(server);
var SSHClient = require('ssh2').Client;

// Load static files into memory
var staticFiles = {};
var basePath = path.join(require.resolve('xterm'), '..');
[ 'addons/fit/fit.js',
  'src/xterm.css',
  'src/xterm.js'
].forEach(function(f) {
  staticFiles['/' + f] = fs.readFileSync(path.join(basePath, f));
});
staticFiles['/'] = fs.readFileSync('index.html');

// Handle static file serving
function onRequest(req, res) {
  var file;
  if (req.method === 'GET' && (file = staticFiles[req.url])) {
    res.writeHead(200, {
      'Content-Type': 'text/'
                      + (/css$/.test(req.url)
                         ? 'css'
                         : (/js$/.test(req.url) ? 'javascript' : 'html'))
    });
    return res.end(file);
  }
  res.writeHead(404);
  res.end();
}

io.on('connection', function(socket) {
  var conn = new SSHClient();
  conn.on('ready', function() {
    socket.emit('data', '\r\n*** SSH CONNECTION ESTABLISHED ***\r\n');
    conn.shell(function(err, stream) {
      if (err)
        return socket.emit('data', '\r\n*** SSH SHELL ERROR: ' + err.message + ' ***\r\n');
      socket.on('data', function(data) {
        stream.write(data);
      });
      stream.on('data', function(d) {
        socket.emit('data', d.toString('binary'));
      }).on('close', function() {
        conn.end();
      });
    });
  }).on('close', function() {
    socket.emit('data', '\r\n*** SSH CONNECTION CLOSED ***\r\n');
  }).on('error', function(err) {
    socket.emit('data', '\r\n*** SSH CONNECTION ERROR: ' + err.message + ' ***\r\n');
  }).connect({
    host: '192.168.100.105',
    username: 'foo',
    password: 'barbaz'
  });
});

server.listen(8000);
  1. Edit the SSH server configuration passed to .connect()in server.js
  2. node server.js
  3. Visit http://localhost:8000in your browser
  1. 编辑SSH服务器配置传递给.connect()server.js
  2. node server.js
  3. 在浏览器中访问http://localhost:8000

回答by giuseppe

Try also noVnc. However, a little dig within the page of xterm.jsreveals other solutions, like

也试试 noVnc。但是,在页面中稍微挖掘一下xterm.js就会发现其他解决方案,例如

WebSSH2

网络SSH2