question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Renci.SshNet.Common.SshException: Failure. exception

See original GitHub issue

Hello,

I have been using the Renci SSH.NET(2016.1.0.0) NuGet package in my web api code, to transfer files from server to a remote SFTP server. This has been working very well for me. The issue I am facing is that I am getting the error marked below. My .NET framework version is 4.6

An exception has been caught during the file upload…:Renci.SshNet.Common.SshException: Failure. at Renci.SshNet.Sftp.SftpSession.RequestOpen(String path, Flags flags, Boolean nullOnError) at Renci.SshNet.SftpClient.InternalUploadFile(Stream input, String path, Flags flags, SftpUploadAsyncResult asyncResult, Action1 uploadCallback) at Renci.SshNet.SftpClient.UploadFile(Stream input, String path, Action1 uploadCallback) at BASF.TAR.RMSService.Controllers.AttachmentController.Get(String sourcepaths, String destinationpath) in d:\Projects\TAR\Samples\BASF.TAR.RMSService\BASF.TAR.RMSService\Controllers\AttachmentController.cs:line 47

I am using the code in my controller as below, its a simple function that takes a source path which is pipe seperated strings and a destination path which is the path on the remote FTP server. The client opens the connection to the server and then in a loop manner each file is uploaded to the remote server and the log is printed.

Please can you let me know why this error is occuring sometimes, any help would be greatly appreciated

public IHttpActionResult Get([FromUri]string sourcepaths, string destinationpath)
        {
            var fileInfo = new List<string>();

            log.Info("Entering the Put() method of the AttachmentController class..");
            try
            {
                using (SftpClient sftp = new SftpClient(ConfigurationManager.AppSettings["SFTP"].ToString(), Convert.ToInt32(ConfigurationManager.AppSettings["Port"].ToString()), ConfigurationManager.AppSettings["UserId"].ToString(), ConfigurationManager.AppSettings["Password"].ToString()))
                {
                    try
                    {
                        if (string.IsNullOrEmpty(sourcepaths) && string.IsNullOrEmpty(destinationpath)) return Ok();

                        var filePaths = sourcepaths.Split('|');
                        sftp.Connect();
                        log.InfoFormat("Connected to SFTP server:{0}..", ConfigurationManager.AppSettings["SFTP"].ToString());
                        
                        log.InfoFormat("Original destination path:{0}", destinationpath);
                        log.InfoFormat("Upload path in the sftp location:{0}", OriginalAttPathToFileSharePath(destinationpath.ToLower()));

                        log.Info("Uploading file...");

                        sftp.ChangeDirectory(OriginalAttPathToFileSharePath(destinationpath.ToLower()));
                        log.InfoFormat("Original destination path:{0}", destinationpath);
                        log.InfoFormat("Upload path in the sftp location:{0}", OriginalAttPathToFileSharePath(destinationpath.ToLower()));
                        foreach (var file in filePaths)
                        {
                            log.InfoFormat("File to be uploaded:{0}", file);
                            using (var stream = new FileStream(file, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
                            {
                                sftp.UploadFile(stream, Path.GetFileName(file), (o) =>
                                {
                                    Console.WriteLine(o);
                                });
                            }
                        }
                        log.Info("File uploaded to server...");
                        sftp.Disconnect();
                    }
                    catch (Exception e)
                    {
                        log.ErrorFormat("An exception has been caught during the file upload..:{0}", e);
                    }
                }
            }
            catch (Exception exp)
            {
                log.Error("Error occured in the Put() method of the AttachmentController class..", exp);
            }
            log.Info("Exiting the Put() method of the AttachmentController class..");
            return Ok();
        }

Issue Analytics

  • State:open
  • Created 4 years ago
  • Comments:7

github_iconTop GitHub Comments

4reactions
worldbeatercommented, Aug 21, 2019

Well, I think I’ve figured out why this is happening to us. If I attempt to use the SSH.NET library on a Windows machine while targeting .NET Core netcoreapp2.1 (not sure, probably .NET Core support is at experimental stage for SSH.NET now), my absolute paths get misinterpreted.

The following line seems to be the cause: https://github.com/sshnet/SSH.NET/blob/13bef36d3811a3811b587c20b33c4ff512dabe93/src/Renci.SshNet/SftpClient.cs#L2051

For example, the following absolute Windows path: C:\Users\usr\AppData\Local\Temp\example_in Gets transformed into the following: /C:/Users/usr/C:/Users/usr/AppData/Local/Temp/example_in

Yeah, /C:/Users/usr repeats twice, and this isn’t a typo! The only way to fix the issue above is to fork the SSH.NET repository, and to replace the line referenced above with somewhat like the following: var fullPath = path; However, this works only for absolute paths, but this was enough in my case.

UPD

Ahh, found another neater way to resolve the issue, all we need to do is to turn the following:

// Breaks with Renci.SshNet.Common.SshException: Failure
sftp.DownloadFile("C:\Users\usr\AppData\Local\Temp\example_in", stream);

Into the following:

// Completes normally.
sftp.DownloadFile("/C:/Users/usr/AppData/Local/Temp/example_in", stream);

And so it works, the same applies to UploadFile too.

// With input like the following path:
// C:\Users\usr\AppData\Local\Temp\example_in
// The snippet below won't throw.
var path = $"/{from.Replace(@"\", "/")}";
sftp.DownloadFile(path, stream);
0reactions
Imbaker1234commented, Jan 14, 2023

Problem

Encountered this error when attempting to call ReadAllFiles during my work on the CES.SquareDUpdater.

I was able to list all of the files, indicating this was not a lack of access, but some implementation detail.


Discovery - 1

I was reading all items in the directory, not just files. Calling ReadAllText on directories causes this very generic failure displayed here.


Solution

After listing all items (files and directories) in my target/parent directory I was searching I filtered out directories.

        public async Task<IEnumerable<string>> ListFiles(string remoteDirectory)
        {
            return await ConnectAndOperate(() => Task.FromResult(_client.ListDirectory(remoteDirectory)
                    .Where(item => !item.IsDirectory) // This is where I made the change.
                    .OrderBy(file => file.LastWriteTimeUtc)
                    .Select(file => file.FullName)),
                $"Listing files in `{remoteDirectory}");
        }

#DevLog

Read more comments on GitHub >

github_iconTop Results From Across the Web

"Renci.SshNet.Common.SshException: Invalid private key ...
"Renci.SshNet.Common.SshException: Invalid private key file" when loading SSH private key from configuration string using SSH.NET · Ask Question.
Read more >
1 Renci.SshNet.Common.SshException: Failure
Hi guys, since last week I get the following error on my Ubuntu Focal: Failed while executing “Backup” with id: 1 Renci.SshNet.Common.
Read more >
UserErrorFailedToReadStream in SFTP Source
HybridDeliveryException, Message=Failed to read data from Sftp server 'sft.nn.com' ... SftpConnector,''Type=Renci.SshNet.Common.SshException ...
Read more >
C# (CSharp) Renci.SshNet.Common SshException ...
C# (CSharp) Renci.SshNet.Common SshException - 6 examples found. These are the top rated real world C# (CSharp) examples of Renci.SshNet.Common.
Read more >
Connect to Linux machine for development, but it doesn't ...
Attempting to connect to a new Virtual Machine is failing. ... SshNet.Common.SshException: Channel was closed. at Renci.SshNet.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found