NodeJS ssh2 sftp客户端|使用公钥和密码连接到sftp



我使用公钥和密码连接到SFTP服务器时遇到问题。我已经尝试了以下代码,但它正在无限调用回调函数。

我感谢您的意见。非常感谢。


let sftpClient = require('ssh2-sftp-client');
let sftp = new sftpClient();
let conf = {
host: 'host',
port: 'port',
username: 'username',
keepaliveInterval: 1000
};
conf.authHandler = function (methodsLeft, partialSuccess, callback) {
console.log('authhandler invoked')
callback({
type: 'publickey',
username: 'username',
passphrase: 'password',
key: fs.readFileSync('./id_rsa.pub', 'utf8')
});
}
sftp.connect(conf).then(() => {
console.log('connected')
// upload process here
}).then(data => {
sftp.end()
}).catch(err => {
console.log(err, 'catch error');
sftp.end()
});

这是我的工作解决方案。你可以在你的服务器上尝试

const sftpClient = require('ssh2-sftp-client');
async upload(file) {
const sftp = new sftpClient();
const sftpSSHKey = fs.readFileSync(keyPath);
try {
await sftp.connect({
host: 'somehost',
port: 'port',
username: 'username',
privateKey: sftpSSHKey,
passphrase: 'passphrase for an encrypted private key',
});
console.log('Successfully connected to sftp');
} catch (error: any) {
console.log(error);
}
try {
const res = await client.put(Buffer.from(file), '/folder/fileName', {
writeStreamOptions: {
flags: 'w',
encoding: null, // use null for binary files
},
});
console.log('File uploaded successfully');
} catch (error) {
console.log(error);
} finally {
await client.end(); // don't forget to close connection
}
}

相关内容

  • 没有找到相关文章

最新更新