我需要使用ssh从远程下载到本地的服务器上的文件。 我正在使用npm link to npm module
中的simple-ssh模块我可以更新服务器上已经存在的文件,但是我需要下载这样的文件
var SSH = require('simple-ssh');
let ssh = new SSH({
host: 'remote_server_ip',
user: 'my_user',
pass: 'my_pass'
});
ssh.exec(`cat > ${filePath}`, {
in: fs.readFileSync('/home/raphael/Documentos/teste.bin')
}).start();
//my filePath /arq_soa/arquivos_validador/Envio/tst_acesso
有人可以帮助我吗,我迷路了
在@Carlos Jafet Neto的帮助下,现在我的代码已更改:
var Client = require('ssh2-sftp-client');
let sftp = new Client
sftp.connect({
host: 'remote_server_iṕ',
port: 22,
username: 'username',
password: 'password'
}).then(() => {
return sftp.list(`${pathArquivoValidador}`);
}).then(async (data) => {
let len = data.length;
await data.forEach(x => {
let remoteFilePath = `${pathArquivoValidador}` + params.nmArquivo;
sftp.get(remoteFilePath).then((stream) => {
let file = './home/raphael/Documentos/' + params.nmArquivo;
fs.writeFile(file, stream, (err) => {
if (err) console.log(err);
});
});
// console.log(x);
});
}).catch((err) => {
console.log(err, 'catch error');
});
但是sftp.get
给我带来了以下错误
{ [Error: ENOENT: no such file or directory, open './home/raphael/Documentos/tst_acesso']
errno: -2,
code: 'ENOENT',
syscall: 'open',
path: './home/raphael/Documentos/tst_acesso' }
答案 0 :(得分:1)
尝试首先获取文件夹中的文件,而不使用变量,将路径用作字符串以消除错误。
var Client = require('ssh2-sftp-client');
let sftp = new Client
sftp.connect({
host: 'remote_server_iṕ',
port: 22,
username: 'username',
password: 'password'
}).then(() => {
return sftp.list('/');
}).then(async (files) => {
console.log(files);
len = files.length;
await files.forEach(x => {
let remoteFilePath = '/' + x.name;
sftp.get(remoteFilePath).then((stream) => {
let file = './ftp/' + x.name;
fs.writeFile(file, stream, (err) => {
if (err) console.log(err);
});
});
});
}).catch((err) => {
console.log(err, 'catch error');
});
要获取单个文件:
var Client = require('ssh2-sftp-client');
let sftp = new Client
sftp.connect({
host: 'remote_server_iṕ',
port: 22,
username: 'username',
password: 'password'
}).then(() => {
let remoteFilePath = '/' + fileName;
sftp.get(remoteFilePath).then((stream) => {
let file = './ftp/' + x.name;
fs.writeFile(file, stream, (err) => {
if (err) console.log(err);
});
sftp.end();
});
}).catch((err) => {
console.log(err, 'catch error');
});
使用此命令关闭ftp连接:
sftp.end();