Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SSHException Channel was closed intermittent behavior #511

Open
Drwal06 opened this issue Jan 22, 2019 · 10 comments
Open

SSHException Channel was closed intermittent behavior #511

Drwal06 opened this issue Jan 22, 2019 · 10 comments

Comments

@Drwal06
Copy link

Drwal06 commented Jan 22, 2019

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
Copy link

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

An existing connection was forcibly closed by the remote host

@mikaelliljedahl
Copy link

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
Copy link

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
Copy link
Member

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

@sachetpatil1
Copy link

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
Copy link

@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:
#377 (comment)

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
Copy link

@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
Copy link

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
Copy link

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
Copy link

raimana commented Jan 16, 2024

For those of you facing this issue, check my comment here #1107 (comment).

TL;DR:

  • Azure Functions have a pool of outbound IP addresses, it can use any for each function execution.
  • Some IPs are allowed by the FTP host, others are blacklisted, hence the intermittent nature of the issue.
  • Run a packet trace from Azure to confirm it's not the remote host closing connections (issue above has details on how to do that)

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

9 participants