Last active
October 28, 2021 04:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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