我需要从.txt.pgp下载一些sftp文件。我试过npm ssh2,ssh2-sftp-client和node-ssh,但都没有成功。
到目前为止,我得到的最接近的文件列表是使用sftp.readdir (ssh2)或sftp.list (ssh2-sftp-client)的远程文件夹中的文件列表。
我尝试过pipe、fs.createWriteStream和sftp.fastGet,但是本地机器上没有保存文件。
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.sftp((err, sftp) => {
if (err) throw err;
sftp.readdir('out', (err, list) => {
if (err) throw err;
list.forEach(item => {
console.log(item.filename);
const fileName = item.filename;
sftp.fastGet(fileName, fileName, {}, downloadError => {
if(downloadError) throw downloadError;
console.log("Succesfully uploaded");
});
})
conn.end();
});
});
}).connect(config);或
const Client = require('ssh2-sftp-client');
const sftp = new Client();
sftp.connect(config).then(() => {
return sftp.list('out');
})
.then(files => {
// console.log(files);
if (files.length > 0) {
console.log('got list of files!');
}
files.map(file => {
const fileName = file.name;
sftp.get(fileName)
.then(() => {
fs.writeFile(fileName);
});
})
})
.then(() => {
sftp.end();
}).catch((err) => {
console.log(err);
});发布于 2018-11-01 21:20:00
关于您的第一次尝试(使用ssh2模块),我可以看到三个问题:
conn.end(),这几乎肯定会导致SSH会话在下载完文件之前关闭。sftp.fastGet()函数提供远程文件的正确路径。在代码的前面,使用远程目录参数'out'调用'out',该参数返回相对于远程目录的文件列表。(要点是:您需要将远程目录放在文件名的前面,以创建一个正确的限定路径。)error,因此我怀疑您没有收到有用的错误消息来帮助解决问题。试一试如下:
const Client = require('ssh2').Client;
const conn = new Client();
const sshOpt = someFunctionThatPopulatesSshOptions();
const remoteDir = 'out';
conn.on('ready', () => {
conn.sftp((err, sftp) => {
if (err) throw err;
sftp.readdir(remoteDir, (err, list) => {
if (err) throw err;
let count = list.length;
list.forEach(item => {
let remoteFile = remoteDir + '/' + item.filename;
let localFile = '/tmp/' + item.filename;
console.log('Downloading ' + remoteFile);
sftp.fastGet(remoteFile, localFile, (err) => {
if (err) throw err;
console.log('Downloaded to ' + localFile);
count--;
if (count <= 0) {
conn.end();
}
});
});
});
});
});
conn.on('error', (err) => {
console.error('SSH connection stream problem');
throw err;
});
conn.connect(sshOpt);这应该解决我提到的所有问题。具体地说:
count变量来确保SSH会话仅在下载所有文件之后才关闭。(我知道它不漂亮。)remoteDir放在所有远程文件下载的前面。error流中的conn事件。https://stackoverflow.com/questions/50180009
复制相似问题