How to connect remote SFTP from Azure web site scheduled job

断了今生、忘了曾经 提交于 2019-12-12 07:23:13

问题


I have one console app which will be scheduled as job in AZURE web site. From that console app I want to connect remote SFTP and get all files and save them in my folder inside AZURE web site.Also if it possible remove them from SFTP after transfer.


回答1:


First of all best and free option to use in this case is WinSCP .NET assembly.

You can download it from here

So lets start this is the function:

public static void GetSftp(string host, string user, string password, int port, string source, string dest, string remoteDest)
    {

        Directory.CreateDirectory(dest);
        var winScpSessionOptions = new SessionOptions
        {
            HostName = host,
            Password = password,
            PortNumber = port,
            UserName = user,
            Protocol = Protocol.Sftp,
            GiveUpSecurityAndAcceptAnySshHostKey = true
        };

        var session = new Session();
        session.Open(winScpSessionOptions);

        var remoteDirInfo = session.ListDirectory(remoteDest);
        foreach (RemoteFileInfo fileInfo in remoteDirInfo.Files)
        {
            if (fileInfo.Name.Equals(".") || fileInfo.Name.Equals("..")) { continue; }
            Console.WriteLine("{0}", remoteDest + fileInfo.Name);
            try
            {

                var x = remoteDest +"/"+ fileInfo.Name;
                var y = dest +"\\"+ fileInfo.Name; 

                var result = session.GetFiles(x, y);

                if (!result.IsSuccess)
                {

                }
                else
                {
                    session.RemoveFiles(remoteDest +"/"+ fileInfo.Name);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }

    }

What this function does? It just gets SFTP credentials and login to SFTP .And lists all file names .And saves each file in AZURE web site ftp.After it removes transferred file.

  • source is SFTP folder
  • Destination where you want to transfer files from SFTP.In AZURE web sites it looks like this D:\home\site\wwwroot\YourFolderName


来源:https://stackoverflow.com/questions/30364881/how-to-connect-remote-sftp-from-azure-web-site-scheduled-job

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!