节点使用ssh从远程计算机读取流文件

时间:2019-05-21 09:23:03

标签: node.js stream ssh2

我正在尝试从不断增长的远程服务器日志文件中读取流中的数据。我想显示添加到本地控制台的新行。我正在使用ssh从本地服务器连接到远程服务器。

我在github上找到了以下解决方案,该解决方案正在将本地文件内容写入远程文件,但我想采用其他方式。没有想法将其反向转换。

var Connection = require('ssh2');
var fs = require('fs');
var BufferedStream = require('buffered-stream');

console.log('sshstream started')
connectSSH();

function readFile(filepath, startOffset, outputStream) {
    var fileSize = fs.statSync(filepath).size;
    var length = fileSize - startOffset;
    var myFD = fs.openSync(filepath, 'r');
    var readable = fs.createReadStream(filepath, {
        fd: myFD, start: startOffset, end: fileSize, autoClose: true
    })
    return readable;
}
function connectSSH(){
    var c = new Connection();
    c.on('connect', function() {
      console.log('Connection :: connect');
    });
    c.on('ready', function() {
      console.log('Connection :: ready');
      c.shell('', function(err, stream) {
        if (err) throw err;         
        stream.on('data', function(data, extended) {
          console.log((extended === 'stderr' ? 'STDERR: ' : 'STDOUT: ')
                      + data);
        });
        stream.on('end', function(code, signal) {
          console.log('Stream :: EOF', code, signal);
        });
        stream.on('close', function(code, signal) {
          console.log('Stream :: close', code, signal);
        });
        stream.on('exit', function(code, signal) {
          console.log('Stream :: exit :: code: ' + code + ', signal: ' + signal);
          c.end();
        });
        stream.on('drain', function() {
          console.log('Stream :: drain');
        });       
            var bufferStream = new BufferedStream(4*1024*1024);
            bufferStream.pipe(stream);
            stream.write('cat - >> /home/username/mylog.log');
            readable = readFile('test.log', 0, bufferStream);
            readable.once('end', function(){
                    console.log("ENDED");
            });
            readable.pipe(bufferStream).pipe(stream);           
        });
    });
    c.on('error', function(err) {
      console.log('Connection :: error :: ' + err);
    });
    c.on('end', function() {
      console.log('Connection :: end');
    });
    c.on('close', function(had_error) {
      console.log('Connection :: close');
    });
    c.connect({
      host: 'xx.xxx.xx.xxx',
      port: 22,
      username: 'username',
      password: 'password'   
    });
}

请提出建议 谢谢

1 个答案:

答案 0 :(得分:1)

这有效,可以根据需要进行自定义。

'use strict';

const SSH = require('simple-ssh');

function run(sshConfig, script) {
  return new Promise((resolve, reject) => {
    let scriptOutput = '';
    const sshFtw = new SSH(sshConfig);
    sshFtw.exec(script,
      { out: console.log.bind(console) })
      .on('error', (err) => reject(err))
      .on('close', () => resolve(scriptOutput))
      .start();
  });
};


run({
  "host": "1.2.3.4",
  "user": "my-user",
  "pass": "my-psw"
}, 'tail -f /home/my-app/log/api-out.log');