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

后端 未结 2 1400
故里飘歌
故里飘歌 2020-12-01 03:19

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-base

2条回答
  •  感动是毒
    2020-12-01 03:50

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

    Here's an example:

    1. npm install ssh2 xterm socket.io
    2. Create index.html:
    
      
        SSH Terminal
        
        
        
        
        
        
      
      
        
    1. Create 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:8000 in your browser

提交回复
热议问题