Quantcast
Channel: SSH.NET Library
Viewing all 2955 articles
Browse latest View live

Commented Unassigned: Session Operation has timed out [2564]

$
0
0
Hi,

I've seen a few posts on this and while I've tried some of the fixes suggested in them, none of them seem to be working. This seems to be present regardless of file size, I've tried a 5MB file, 20MB, 100MB and 512MB...the final solution if I can get this working needs to be capable of transferring about 10GB or so.

I'm still getting to grips with this library so it might be something that I'm doing wrong and not in fact an issue at all, but looking round I've seen a few pieces here and there so it might be a recurring issue. I have also tried with just the standard buffersize, but seeing the suggestions that this might fix it, I added in the line to specify it explicitly.

Testing it with the SFTP client results in a successful transfer and a very quick one at that, although it is going from host to guest VM so that is to be expected!

Thinking it might be something to do with how I'm initializing the I took a look inside the ConnectionInfo and saw that the client is using SSH2.0 could this be affecting the size?

I have also tested the transfer using the Putty SCP command line tool and it successfully completes without any issues.

```
sshClient.Connect();
if (sshClient.IsConnected)
{
try
{
Console.WriteLine("Connection successful!");
Console.WriteLine();
Console.WriteLine(string.Format("Checking for existence of {0} directory...", destDir));
var locateDir = sshClient.RunCommand(string.Format("if [ -d {0} ]; then echo \"true\"; else echo \"false\"; fi", destDir));
var dirExixts = Convert.ToBoolean(locateDir.Result.Replace("\n", ""));
if (dirExixts)
{
Console.WriteLine("Directory already exists...");
}
else
{
Console.WriteLine("Directory not found, attempting to create directory...");
var createDir = sshClient.RunCommand(string.Format("mkdir {0}", destDir));
if (createDir.ExitStatus == 0)
Console.WriteLine("Destination directory successfully created!");
else
{
throw new Exception(string.Format("Failed to create remote directory: {0}. Error: {1}", destDir, createDir.Error));
}
}

Console.WriteLine();
Console.WriteLine("Initiating SCP transfer...");
var scpClient = new ScpClient(sshClient.ConnectionInfo);
scpClient.BufferSize = 1024 * 16 - 64;
scpClient.Connect();
var file = new FileInfo(@"C:\Users\DevTest\Downloads\20MB.zip");
using (var stream = File.OpenRead(file.FullName))
{
scpClient.Upload(stream, destDir + "/" + file.Name);
}
Console.WriteLine("SCP transfer complete!");
Console.WriteLine();
Console.WriteLine(string.Format("Disconnection from {0}..."));

sshClient.Disconnect();

Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("An unexpected error has occured");
Console.WriteLine(string.Format("Exception: {0}", ex.Message));
sshClient.Disconnect();
}
}
else
{
Console.WriteLine("Connection failed...");
}
```

If needs be as well, I am running this in a VM so can snapshot and sort out sending a copy of the environment over to see if you're able to reproduce in.

After some more digging, specifically finding this site http://winscp.net/eng/docs/scp it looks like SCP has a file size maximum of 4GB anyway making it impractical for the 10GB target I need to hit, however the SFTP function works fine so I can carry on with that aspect of this library but some insight into the issue anyway would be interesting.
Comments: ** Comment from web user: drieseng **

Let me know where I can download the VM so I can try to reproduce the issue.


Edited Issue: System.NullReferenceException [2013]

$
0
0
Hi All

I have written a program that only downloads a part of the file using SFTP and adds it to the previously downloaded file. Basically resumes download.

Program works perfectly except when I am testing varies conditions for example losing connection ect.

This code is running in a timer.

To reproduce the error:
1. Put a break on "remote.CopyTo(fs, (int)sftp.BufferSize);"
2. Put a break on "catch (System.Net.Sockets.SocketException)"
3. Start timer to run code.
4. As the copy process starts remove network cable (trying to simulate losing connection).
5. Exception will be thrown "System.Net.Sockets.SocketException" after awhile.
6. Plug network cable in.
7. The code will try run again when the timer is triggered and after a random time the exception "System.NullReferenceException" will be thrown(Doesnt take long).

Full Error:
An unhandled exception of type 'System.NullReferenceException' occurred in Renci.SshNet.dll

Additional information: Object reference not set to an instance of an object.

If I break then I see these lines:
Call stack with external code
Renci.SshNet.dll!Renci.SshNet.Sftp.SubsystemSession.SendData(byte[] data)
Renci.SshNet.dll!Renci.SshNet.Sftp.SftpSession.SendMessage(Renci.SshNet.Sftp.SftpMessage sftpMessage)
Renci.SshNet.dll!Renci.SshNet.Sftp.SftpSession.SendRequest(Renci.SshNet.Sftp.Requests.SftpRequest request)
Renci.SshNet.dll!Renci.SshNet.Sftp.SftpSession.RequestClose(byte[] handle)
Renci.SshNet.dll!Renci.SshNet.Sftp.SftpFileStream.Dispose(bool disposing)
Renci.SshNet.dll!Renci.SshNet.Sftp.SftpFileStream.Finalize()
[Native to Managed Transition]

My Code
```
private int Download(string IP, string UserName, string Password, string FileSource, string Num)
{
int fault = 0;

SftpClient sftp = null;

try
{
using (sftp = new SftpClient(IP, UserName, Password))
{
Logging.Log_To_file("SFTP connecting");
sftp.Connect();
Logging.Log_To_file("SFTP ok");

Int64 length;
using (FileStream check = File.OpenWrite(root + num+ @"\" + OldFile))
{
length = check.Length;
}

using (FileStream fs = File.Create(root + num+ @"\" + PartFile))
{
using (SftpFileStream remote = sftp.OpenRead(FileSource))
{
Int64 length2 = remote.Length;
if (length > length2)
{
remote.CopyTo(fs, (int)sftp.BufferSize);
}
else
{
remote.Seek(length, SeekOrigin.Begin);

remote.CopyTo(fs, (int)sftp.BufferSize);
}
}
}

Logging.Log_To_file("SFTP disconnecting...");
sftp.Disconnect();
Logging.Log_To_file("SFTP Done");
sftp.Dispose();
Logging.Log_To_file("SFTP Disposed");
}
}
catch (SshAuthenticationException)
{
Logging.Log_To_file("Permission denied");

fault = 1;
}
catch (SftpPathNotFoundException)
{
Logging.Log_To_file("No such file");

fault = 1;
}
catch (System.Net.Sockets.SocketException)
{
Logging.Log_To_file("Connection timed out");

fault = 1;
}
catch (Exception e)
{
Logging.Log_To_file("Unknown error occurred with SFTP");

fault = 1;
}
return fault;
}
```

Any help with this problem would be much appreciated, thanks.
Comments: ** Comment from web user: drieseng **

In this case the cause is probably this:

The SocketException that was thrown because of the connection loss caused the Dispose() method of SftpFileStream to be invoked.

In the Dispose(bool) method of SftpFileStream we try to close the FXP file handle. This probably failed because the session was closed (due to the loss of connectivity).

Some time later, the GC attempts to finalize the SftpFileStream invoking the Dispose(bool) method again.
In the meantime the session has been disposed, causing the channel to be null.
So when the session attempts to send data through the channel to close the FXP file handle, this causes a NullReferenceException.

I'll modify SftpFileStream to only attempt to close the FXP file handle when the SftpFileStream is being disposed (though invocation of the Dispose() method), and not when being finalized.

Source code checked in, #40805

$
0
0
Remove redundant this qualifiers. Change SubsystemSession._operationTimeout into a read-only OperationTimeout property. FlagsAttribute is used as a bit field, so mark it as such.

New Post: ObjectDisposedException Exception on SendKeepAlive()

$
0
0
Hello all

I'm using the ssh.net library in a project, which creates quite a lot of SSH connections to a host. For this I am using a pool of open SSH connections and disconnect them after a while if not used.

Establishing a connection is done as follows:
SshClientObject = new SshClient(_Host, _Username, _Password);
SshClientObject.KeepAliveInterval = new TimeSpan(0,0,1,0);
SshClientObject.Connect();
Disconnect is done as follows:
SshClientObject.Disconnect();
SshClientObject.KeepAliveInterval = new TimeSpan(-1);
SshClientObject.Dispose();
SshClientObject = null;
In rare cases I have an unhandled exception, which terminates the application (Windows Service):

at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags, SocketError& errorCode)
at Renci.SshNet.Session.SocketWrite(Byte[] data)
at Renci.SshNet.Session.SendMessage(Message message)
at Renci.SshNet.BaseClient.SendKeepAlive()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.TimerQueueTimer.CallCallback()
at System.Threading.TimerQueueTimer.Fire()
at System.Threading.TimerQueue.FireNextTimers()

It seems that even when I set the KeepAliveInterval to -1 (should disable), the KeepAlive timer seems to fired after I have disposed the object.

I would think that disposing an object also stops all timers, expechally when I first disable the KeepAliveInterval.

Any idea how I could prevent this exception?

I'm using the latest stable Version (2013.4.7).

Philipp

Created Unassigned: ObjectDisposedException Exception on SendKeepAlive() [2572]

$
0
0
Hello

It seems that in certain cases the KeepAlive timer is not stoped on dispose() of the ssh object.

See description in the question: [TEXT](https://sshnet.codeplex.com/discussions/571684)

The results in a ObjectDisposedException and crashes the application.

A fix would be appreciated.
Philipp

Commented Unassigned: ObjectDisposedException Exception on SendKeepAlive() [2572]

$
0
0
Hello

It seems that in certain cases the KeepAlive timer is not stoped on dispose() of the ssh object.

See description in the question: [Question in discussion forum](https://sshnet.codeplex.com/discussions/571684)

The results in a ObjectDisposedException and crashes the application.

A fix would be appreciated.
Philipp
Comments: ** Comment from web user: drieseng **

Philipp,

This should be fixed in the latest beta release.
Can you confirm this ?

Cheers,
Gert

Source code checked in, #40807

$
0
0
Implemented basic tests for SemaphoreLight.

Source code checked in, #40808

$
0
0
Added basic tests for Pipestream.

Source code checked in, #40809

$
0
0
Added missing checks for availability of session.

Commented Unassigned: SendKeepAlive fails: An established connection was aborted by the software in your host machine [2029]

$
0
0
Seems like library does not handle Socket Exceptions gracefully in all cases.
If I set time span value for SendKeepAlive and connection is lost System.Net.Sockets.SocketException exception is thrown. As far as I understand, no exceptions should be thrown but OnError event should be raised?

I'm using version 2013.4.7, but tried with current source with same results.
I've fixed it for myself by wrapping it with try / catch in SendKeepAlive method in Session.cs, so it looks like this now

```
internal void SendKeepAlive()
{
try
{
this.SendMessage(new IgnoreMessage());
}
catch (Exception exp)
{
this.RaiseError(exp);
}
}
```

Thank you for your work, regards.


```
Exception: An established connection was aborted by the software in your host machine
ErrorCode: 10053
at Renci.SshNet.Session.SocketWrite(Byte[] data)
at Renci.SshNet.Session.SendMessage(Message message)
at Renci.SshNet.BaseClient.SendKeepAlive()
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.TimerQueueTimer.CallCallback()
at System.Threading.TimerQueueTimer.Fire()
at System.Threading.TimerQueue.FireNextTimers()
```
Comments: ** Comment from web user: tibotabo **

I have the same effect, for me it happens if the SSH server unexpectedly dies / gets killed.

New Post: ASP.NET SSH Client

$
0
0
 I'm a ASP.NET developer who has a client that wants a web based SSH client for their intranet.  I've never used SSH so I'm this is a new thing for me.  Is there a complete ASP.NET web client project that I can download and use as a learning tool and customize for my client?  Any help would be greately appreciated!!!

Commented Issue: Exists function returns always true for any file [1952]

$
0
0
See attached test source. Some old version of ssh.net worked fine.
Comments: ** Comment from web user: ygorcardoso **

Hi,

Is there any estimate to when the release with this changeset will be available? This is quite an important part of the SFTP functionality of this library, the use of other functionalities may depend on this one.

New Post: Check if Directory exists with SSH.NET

$
0
0
Hi,

Is there any estimate to when the release with this changeset will be available? This is quite an important part of the SFTP functionality of this library, the use of other functionalities may depend on this one.

Cheers,
Ygor

New Post: File upload failing - need help

$
0
0
I am currently trying to upload a file via sFTP:
        public bool UploadFile(Settings settings, string localPath)
        {
            try
            {
                using (var sftp = new SftpClient(settings.Host, settings.Username, settings.Password))
                {
                    sftp.Connect();
                    using (var fileStream = File.OpenRead(localPath))
                    {
                        sftp.UploadFile(fileStream, settings.RemoteDirectory, true);
                    }
                    sftp.Disconnect();
                }
                return true;
            }
            catch (Exception ex)
            {
                Utility.Err(ex, "UploadFile()");
                return false;
            }
        }
The error message I am getting is:
Renci.SshNet.Common.SshException was caught
  HResult=-2146233088
  Message=Failure
  Source=Renci.SshNet
  StackTrace:
       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, Action`1 uploadCallback)
       at Renci.SshNet.SftpClient.UploadFile(Stream input, String path, Boolean canOverride, Action`1 uploadCallback)
       at Renci.SshNet.SftpClient.UploadFile(Stream input, String path, Action`1 uploadCallback)
       at MyProj.Models.MyClass.UploadFile(Settings settings, String localPath) in c:\Users\Me\Documents\Visual Studio 2013\Projects\MyProj\MyProj\Models\MyClass.cs:line 19
  InnerException: 
There is no inner exception given

The remote directory I am trying to upload to is "./inbound/". When downloading, using "./outbound/" works fine.

Any help will be appreciated

New Post: File upload failing - need help

$
0
0
The issue was I needed to append the intended file name on the remote directory like so:
public bool UploadFile(Settings settings, string localPath, string fileName)
        {
            try
            {
                using (var sftp = new SftpClient(settings.Host, settings.Username, settings.Password))
                {
                    sftp.Connect();
                    using (var fileStream = File.OpenRead(localPath))
                    {
                        var remotePath = settings.RemoteDirectory + fileName;
                        sftp.UploadFile(fileStream, remotePath, true);
                    }
                    sftp.Disconnect();
                }
                return true;
            }
            catch (Exception ex)
            {
                Utility.Err(ex, "UploadFile()");
                return false;
            }
        }
Now i just pass in the filename, and append it to the remote directory

The same is true for renaming files, both strings will need the full path and file name:
        public bool RenameRemoteFile(Settings settings, string oldFilePath, string newFilePath)
        {
            try
            {
                using (var sftp = new SftpClient(settings.Host, settings.Username, settings.Password))
                {
                    sftp.Connect();
                    sftp.RenameFile(oldFilePath, newFilePath);
                    sftp.Disconnect();
                }
                return true;
            }
            catch (Exception ex)
            {
                Utility.Err(ex, "RenameRemoteFile()");
                return false;
            }
        }

Commented Issue: Exists function returns always true for any file [1952]

$
0
0
See attached test source. Some old version of ssh.net worked fine.
Comments: ** Comment from web user: spidercode **

@ygorcardoso : I think this issue has already been solved in current beta version.

Commented Issue: Exists function returns always true for any file [1952]

$
0
0
See attached test source. Some old version of ssh.net worked fine.
Comments: ** Comment from web user: ygorcardoso **

@spidercode thank you for your answer, but it was not updated in the [nuget package](http://www.nuget.org/packages/SSH.NET/2014.4.6-beta1); the package was last updated in April 6th, this was just fixed in [May 4th](https://sshnet.codeplex.com/SourceControl/changeset/35724)

Commented Unassigned: ObjectDisposedException Exception on SendKeepAlive() [2572]

$
0
0
Hello

It seems that in certain cases the KeepAlive timer is not stoped on dispose() of the ssh object.

See description in the question: [Question in discussion forum](https://sshnet.codeplex.com/discussions/571684)

The results in a ObjectDisposedException and crashes the application.

A fix would be appreciated.
Philipp
Comments: ** Comment from web user: iphphilipp **

Gert,

I integrated the beta version now and am letting the application run in the test environment. However the error shows up very rare. It will take a moment to really tell.

Regards,
Philipp

New Post: SCP upload speed

$
0
0
Thanks a lot for input!
Input stream is a networked file (100MBit/s, LAN), also, it is a single 30MB file.
Unfortunately, cannot make the server available. :)

Source code checked in, #40819

$
0
0
Channel: * Only send SSH_MSG_CHANNEL_EOF message to remote party when we haven't received a SSH_MSG_CHANNEL_EOF or SSH_MSG_CHANNEL_CLOSE message from the remote party. * Move logic for sending SSH_MSG_CHANNEL_EOF message from derived classes and client classes into Channel.Close(bool) method. * Move initialization to ctor. ChannelSession: * Avoid leaking session semaphores. SftpFileStream: * Modify CanRead, CanWrite and CanSeek to return false when the stream is disposed. * Modify other public members to throw ObjectDisposedException when the stream is disposed or the SFTP session is no longer open. * Modify Dispose to only flush the write buffer and/or close the SFTP file handle when the SFTP session is open. * No longer flush write buffer or close SFTP file handle in finalizer. Fixes issue #2013. Session: * Remove CreateClientChannel<T> and CreateServerChannel<T> methods; use specific constructors of channels instead. SftpClient: * BufferSize was not used for AppendText(String, Encoding) and Create(String) overloads. SubsystemSession: * Added IsOpen property. * Throw ObjectDisposedException in all public members - except for IsOpen - when the session is disposed. * Throw InvalidOperationException in all public members - except for Connect and IsOpen - when the session is not open. * Modify Disconnect to release managed resources that are linked to the connected session. * Modify Dispose to use Disconnect to managed resources that are linked to the connected session. Unit tests: * Added large set of tests for changes listed above. * Tests for which the code was automatically, and that are not yet correctly implemented, are now marked as Ignore. * Tests that require a (specifically configured) running SSH server are now marked with test category "integration".
Viewing all 2955 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>