Skip to content

Instantly share code, notes, and snippets.

@adi928
Created August 28, 2021 20:13
Show Gist options
  • Save adi928/cb7294db0265b4fe5542561ca6599c60 to your computer and use it in GitHub Desktop.
Save adi928/cb7294db0265b4fe5542561ca6599c60 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Renci.SshNet;
using Azure.Storage.Blobs;
using Microsoft.WindowsAzure.Storage.Auth;
namespace content_delivery
{
public class blobToFtpObj
{
public string source_containerName;
public List<string> fileNames;
public string dest_ftpName; # For eg. ftpHost.organization.com@/root/flag.txt
public override string ToString()
{
return "Move declared: From " + source_containerName + " to " + dest_ftpName;
}
}
public static class blobToFtp
{
// Enter your sftp username here
private static string username = "blobToFtp_user";
// Enter your sftp password here
private static string password = "somePassword";
private static bool validRequest(blobToFtpObj reqObj){
return true;
}
[FunctionName("blobToFtp")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
# Change this to hold how much ever objects you want at a single time.
# This can directly relate to the amount of concurrency you'd want in your app
# Consequenctially, how far you would want the function app to scale vertically.
List<blobToFtpObj> reqObj = new List<blobToFtpObj>(10);
reqObj = JsonConvert.DeserializeObject<List<blobToFtpObj>>(requestBody);
string ftpPath = reqObj[0].dest_ftpName.Split('@')[1];
string ftpHost = reqObj[0].dest_ftpName.Split('@')[0];
var connectionInfo = new SftpClient(ftpHost, username, password);
string connectionString = "DefaultEndpointsProtocol=https;AccountName=reportDatabase;AccountKey=/6+FuuGanaskjdfbasjdbudJKHASsZEuwG0uqe+Da==;EndpointSuffix=core.windows.net";
BlobContainerClient container = new BlobContainerClient(connectionString, reqObj[0].source_containerName);
var blockBlob = container.GetBlobClient(reqObj[0].fileNames[0]);
MemoryStream mstream = new MemoryStream();
blockBlob.DownloadTo(mstream);
# May not need this line
mstream.Seek(0, SeekOrigin.Begin);
try
{
connectionInfo.Connect();
log.LogInformation("SFTP Connect Success");
connectionInfo.BufferSize = 1024;
connectionInfo.UploadFile(mstream, ftpPath);
connectionInfo.Dispose();
}
catch (Exception e)
{
return BadRequestObjectResult(e)
}
finally{
connectionInfo.Disconnect();
}
return new OkObjectResult("HTTP finished properly");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment