gpt4 book ai didi

node.js - Node 使用 ssh 从远程计算机读取文件流

转载 作者:太空宇宙 更新时间:2023-11-03 22:57:39 27 4
gpt4 key购买 nike

我正在尝试从不断增长的远程服务器日志文件中读取流中的数据。我想显示添加到本地控制台的新行。我正在使用 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'
});
}

请推荐谢谢

最佳答案

这可行,并且可以根据您的意愿进行自定义。

'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');

关于node.js - Node 使用 ssh 从远程计算机读取文件流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56235160/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com