我在使用公钥和密码连接到 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 sftp.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 sftp.end(); // don't forget to close connection
}
}