Skip to content

Instantly share code, notes, and snippets.

@palanisamym14
Last active October 28, 2021 04:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save palanisamym14/298fc7762fea11da84eefc232e57a322 to your computer and use it in GitHub Desktop.
Save palanisamym14/298fc7762fea11da84eefc232e57a322 to your computer and use it in GitHub Desktop.
ssh2-sftp-client - Test sftp connection using aws lambda, input should be passed array of object
const AWS = require('aws-sdk');
const SSM = new AWS.SSM();
const fs = require('fs');
let Client = require('ssh2-sftp-client');
function clean(obj) {
for (var propName in obj) {
if (obj[propName] === null || obj[propName] === undefined) {
delete obj[propName];
}
}
return obj
}
const getSSMPrivateKey = async (config) =>{
let responseFromSSM = null
var parameter = {
"Name" : config.privateKey
};
responseFromSSM = await SSM.getParameter(parameter).promise();
console.log('SUCCESS');
const value = responseFromSSM.Parameter.Value;
return value
}
const sftpConnection = async (sftpConfig) => {
try {
const privateKey = sftpConfig.privateKey ? await getSSMPrivateKey(sftpConfig): null;
const config = {
host: sftpConfig.host,
user: sftpConfig.userName,
port: sftpConfig.port || 22,
password: sftpConfig.password || null,
privateKey: privateKey || null,
passphrase: sftpConfig.passphrase || null,
}
console.log(config.host);
console.log(config.user);
const client = new Client();
await client.connect({
...clean(config),
});
console.log(`Client Connected`);
if (sftpConfig.remoteDir) {
const result = await client.list(sftpConfig.remoteDir);
console.log(result);
// console.log(await client.list(sftpConfig.remoteDir));
console.log(sftpConfig.remoteDir);
}
return true;
} catch (err) {
console.log(err)
return true;
}
}
exports.handler = async (event) => {
try {
for (let config of event) {
await sftpConnection(config);
}
const response = {
statusCode: 200,
body: { status: 'success' },
};
return response;
} catch (error) {
console.log(JSON.stringify(error))
return true;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment