sshnet / SSH.NET

SSH.NET is a Secure Shell (SSH) library for .NET, optimized for parallelism.
http://sshnet.github.io/SSH.NET/
MIT License
4.03k stars 934 forks source link

SSHException Channel was closed intermittent behavior #511

Open Drwal06 opened 5 years ago

Drwal06 commented 5 years ago

We are connecting to a client SFTP and prior to this week had nothing but successful transactions. We are now experiencing intermittent exceptions. We are calling this functionality from an Azure function, and the files are streamed from Azure storage, but i don't believe that has any impact on the issue. I have tried both synchronous and asynchronous methods and had success locally, and on majority of live test cases, but when it fails, I don't have an idea of what the problem may be. Any thoughts would be much appreciated.

My code is below:

sftpClient.Connect(); var uploadPath = $"{sftpFolder}/{fileName}"; sftpClient.UploadFile(stream, uploadPath); sftpClient.Disconnect();

Alternatively, I tried instead:

sftpClient.Connect(); var uploadPath = $"{sftpFolder}/{fileName}"; var returnVal = sftpClient.BeginUploadFile(stream, uploadPath, new AsyncCallback(x => FileTransferred(x, log, fileName, uploadPath)));

andrewralon commented 5 years ago

Any luck on this? I'm getting a SocketException:

An existing connection was forcibly closed by the remote host

mikaelliljedahl commented 5 years ago

I am having a similar problem with Azure but not with all hosts. It is also intermittent. Sometimes i get this error An existing connection was forcibly closed by the remote host Stack Trace: at Renci.SshNet.SubsystemSession.WaitOnHandle(WaitHandle waitHandle, Int32 millisecondsTimeout) at Renci.SshNet.Sftp.SftpSession.RequestRealPath(String path, Boolean nullOnError) at Renci.SshNet.Sftp.SftpSession.GetCanonicalPath(String path) at Renci.SshNet.SftpClient.InternalListDirectory(String path, Action`1 listCallback)

and sometimes i already get the error on Connect: at Renci.SshNet.Abstractions.SocketAbstraction.Connect(IPEndPoint remoteEndpoint, TimeSpan connectTimeout):

Couln't connect to SFTP A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond

I have set up our own SFTP server (freeFTPd) and could replicate the problem.

Running the same code on my dev machine I never experience the problem.

itsashish-patel commented 5 years ago

I am having a similar problem with Azure Function with some request but not all. below is code, do I need to use static or singleton sftp client to overcome from this issue?

using (SftpClient client = new SftpClient(ftpModel.Host, ftpModel.Port, ftpModel.UserName, ftpModel.Password)) { client.Connect(); using (MemoryStream fs = new MemoryStream(ftpModel.Content)) { client.BufferSize = 4 * 1024; client.UploadFile(fs, $"{ftpModel.FilePath}/{ftpModel.FileName}"); } }

drieseng commented 4 years ago

Sorry for being late to this party. Were you able to rule out network issues?

sachetpatil1 commented 4 years ago

Anyone got solution for this issue??

I am also facing same issue (Calling Renci from Azure function). Although credentials works fine with same code in Dev and Test environment and files successfully transferring to server but after deploying in UAT it got failed with this error :(

mikaelliljedahl commented 3 years ago

@sachetpatil1 I only get this error intermittently now, but I have not updated to the latest version.

But when switching to .Net Core 2 years ago I got it the whole time. So I took the latest version of the code, not the nuget) and applied the change suggested here: https://github.com/sshnet/SSH.NET/issues/377#issuecomment-548962727

I still have not merged the last version and tested it with the last fixes and/or that change.

This seems like this could be an Azure (SNAT?) related issue (agressively low timeout settings perhaps?), but it would be nice if the client library could cope with it, e.g. through a retry (if that is possible), chattier keep-alives or something in that direction.

I have also gotten a similar error when downloading av large file, like 200 mb which I think is odd. I am running that download inside an async thread, I don't know if that is relevant.

sachetpatil1 commented 3 years ago

@mikaelliljedahl After so much investigation, we decided to speak with our Azure admin team (different organisation) and got to know that they restricted FTP server to connect external resourves in firewall so that App service IP was not allowed to connect FTP server. We requested them to whitelist that IP and it worked.

I feel there is no issue in Renci dll regarding connection to external ftp. Now we are able to send all files but not sure how much file size it can handle (Curently we are sending max 100 mb file).

alirizatemel commented 2 years ago

I was getting this error from windows server and I found the solution on this page ; https://superuser.com/a/1733719/1747814 Don't let the negative points fool you.

justdomyself commented 1 year ago

my code : `public void sftp() { using (var client = new SftpClient(host, username, password) ) { try { client.Connect();

                if (client.IsConnected)
                {
                    Console.WriteLine("SFTP connection established.");

                    // 上传文件到远程服务器
                    using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello, remote server!")))
                    {
                        client.UploadFile(stream, "/path/to/remote/file.txt");
                        Console.WriteLine("File uploaded to remote server.");
                    }
                }
                else
                {
                    Console.WriteLine("Failed to establish SFTP connection.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
            finally
            {
                if (client.IsConnected)
                {
                    client.Disconnect();
                    Console.WriteLine("SFTP connection closed.");
                }
            }
        }
    }`

error:

引发的异常:“Renci.SshNet.Common.SshException”(位于 Renci.SshNet.dll 中) An error occurred: Channel was closed.

raimana commented 10 months ago

For those of you facing this issue, check my comment here https://github.com/sshnet/SSH.NET/issues/1107#issuecomment-1892870568.

TL;DR:

FWIW: I've published a minimal reproduction (using Durable Functions) implementing both SSH.NET and WinSCP. See here: https://github.com/raimana/ConnectionClosedIssueReproduction