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

New Post: Pageant integration?

$
0
0
Thanks sorry the original patchset is available still I was asking about the updated patch set that was mentioned above (http://wikisend.com/download/770862/Pageant.zip) that is dead. The original patches don't apply cleaning to the current source (they override files rather than patch them anyway and don't compile).

One could pull the original sources from around the time of the original patch set, apply them, make proper patches but it seems:
https://github.com/dimov-cz/win-sshfs
integrates atleast some level of the patches so using that may be easiest for anyone else trying to get paegent support.

New Post: Upload Issue

$
0
0
Hi Team,

when i am trying to upload file using SSH.net i am getting below error:

Renci.SshNet.Common.SshException was unhandled
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 ConsoleApplication2.Program.FileUploadUsingSftp() in C:\Users\armahe\documents\visual studio 2010\projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 52
   at ConsoleApplication2.Program.Main(String[] args) in C:\Users\armahe\documents\visual studio 2010\projects\ConsoleApplication2\ConsoleApplication2\Program.cs:line 15
   at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
   at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
   at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
   at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.ThreadHelper.ThreadStart()
InnerException:

i have one file at my local system at location "D:/Test/test.xml.PGP" and want to upload this file to SFTP at location
@SFTP_HOST/SFTP_TestFolder/(here i want to place 'test.xml.PGP' file). For this i have written this piece of code.

var RenciSFTP = new Renci.SshNet.SftpClient(sftpHost, username, password);
string filePath = @"D:/Test/test.xml.PGP";
using (Stream fileStream = File.OpenRead(filePath))
            {                    
                RenciSFTP.ConnectionInfo.Timeout = new TimeSpan(0, 5,00);
                Console.WriteLine("Connecting...{0},{1},{2}", sftpHost, username, password);
                RenciSFTP.Connect();
                Console.WriteLine("connected,  uploading file from location :", fileName);

                var remotePath = "./" + fileName;

                RenciSFTP.UploadFile(fileStream, "/SFTP_TestFolder",true);
                RenciSFTP.Disconnect();
            }

New Post: help with execute command with quotes escaping

$
0
0
Hello,
I try to run the command date -s "Tue Feb 10 13:15:12 UTC 2015"
in code:
ShellStream..WriteLine("date –s \"" + date + "\""); // when date contain "Tue Feb 10 13:15:12 UTC 2015"
i keep getting date extra operand (original message):
date: extra operand `Tue Feb 10 14:21:01 UTC 2015'

should i need different escaping?
thank you
Lior.

New Post: ssh.net More Info and samples for streams

$
0
0
New User here,
Can I get a more recent example of how to use a stream and expect to get streams to work...using Cisco which want to disconnect after every command. I have partially been able to use 'expect' with success but still not quite sure what it is exactly doing.


Many examples seem years old.

What is the best way to run multiple long output commands with examples please (FOR C#)

Thank you

Created Unassigned: StackOverflowException thrown on Connect() [2620]

$
0
0
During a test I wanted to force an exception to be thrown while connecting to my SFTP server.

To my surprise the exception took down the whole process when I added an uncerscore ("_") to my password.

The StackOverflowException is thrown after a couple of minutes:
"An unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll"

I am using SSH.NET.2014.4.6-beta2 taken from Nuget.

I am connecting using a combination of username/password and a private key.

New Post: SCP options...

$
0
0
Hi,
Is there plan to allow user to set the SCP options ? I am using SCP download function from ScpClient.NET.cs and would like to change the option scp -prf to scp -rf .
Doing this increases the transfer speed by 30%.
Any input on this will be helpful.
Thanks,
AG

New Post: ssh.net More Info and samples for streams

$
0
0
Here is what I have that works
client.Connect();

using (ShellStream shellStream = client.CreateShellStream("dumb", 80, 24, 800, 600, 1024))
{
 var reader = new StreamReader(shellStream);
 var writer = new StreamWriter(shellStream);

 writer.AutoFlush = true;

 while (shellStream.Length == 0)
 {
     Thread.Sleep(500);
 }

 Regex userPromptMatch = new Regex(@"#");
 
 string prompt = shellStream.Expect(userPromptMatch, new TimeSpan(0, 1, 0));
 WriteStream("term length 0", writer, shellStream);
 Console.WriteLine(prompt);
 
 string result = shellStream.Expect("term length 0", new TimeSpan(0, 1, 0));
 Console.WriteLine(result); 
 WriteStream("show int desc", writer, shellStream);
 
 result = shellStream.Expect("show int desc", new TimeSpan(0, 1, 0));
 Console.WriteLine(result);

 string final = shellStream.Expect(prompt, new TimeSpan(0, 1, 0));
 Console.WriteLine(final);

using (writer = File.AppendText(@"C:\Users\test.txt"))
{
 writer.WriteLine(final);
}

}

 client.Disconnect();
                                    
}

 private static void WriteStream(string cmd, StreamWriter writer, ShellStream stream)
        {
            writer.WriteLine(cmd);
            while (stream.DataAvailable == false)
            {
                Thread.Sleep(1000);
            }

        }

Patch Uploaded: #17236

$
0
0

onehourlate has uploaded a patch.

Description:
Hi,

I had a couple of issues while using scp with cisco routers

1) the scp commands (scp -t or scp -f) uses double quotes to escape the file name. That's not supported if the other end doesn't have a shell that understands that. So the patch adds the quote only if necessary (that is, if the file contains whitespace chars). It cas it adds quotes, it also escapes any inner quote in the file name. Cf ScpClient.QuoteIfNeeded method

2) the Upload(Stream source, string path) method didn't work at all because the scp -t command was never sent if the filename didn't contain a '/' or '\'

3) Disposing of the scp session tended to throw an exception because the other end had already closed it. I didn't try to hard to understand, but I added code to swallow the SocketException with error code 10054 (WSAECONNRESET cf https://msdn.microsoft.com/en-us/library/windows/desktop/ms740668%28v=vs.85%29.aspx) in method Session.SocketDisconnect . No point raising an exception on close because the other end already closed the socket I think.


Created Unassigned: renci.sshnet - Problem with execute su - user [2623]

$
0
0
Hi all, i write this code for connect with a server in SSH with vb2010:

Public Class Form1

'Create the objects needed to make the connection'
Dim connInfo As New Renci.SshNet.PasswordConnectionInfo("10.177.192.19", "admin", "pwd")
Dim sshClient As New Renci.SshNet.SshClient(connInfo)
'Need to hold the command'
Dim cmd As Renci.SshNet.SshCommand
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Using sshClient
sshClient.Connect() 'connect to the server'
cmd = sshClient.RunCommand("hostname")
lblserver.Text = cmd.Result
Me.Refresh()

cmd = sshClient.RunCommand("su - guest")
If cmd.Error <> "" Then
TextOutput.Text = cmd.Error
sw.WriteLine(Replace(cmd.Error, Chr(10), vbCrLf))
Else
TextOutput.Text = Replace(cmd.Result, Chr(10), vbCrLf)
sw.WriteLine(Replace(cmd.Result, Chr(10), vbCrLf))
End If
sshClient.Disconnect()

end sub

The problem occurs when you run the line "cmd = sshClient.RunCommand("su - guest")", the program stops responding and does not go forward.
Why?
Help me please...
Thank's

New Post: Renci.SshNet.Common.SshOperationTimeoutException

$
0
0
I'm getting the same error when calling SftpClient.UploadFile() to upload a large-ish file (~600Mb) to a FreeBSD UNIX file server, it fails after transferring half the file (several minutes later).
I'm using SSH.NET 2014.4.6-beta2.
Maybe I should be using the asynchronous upload, sftp.BeginUploadFile(). Any thoughts/suggestions?
Renci.SshNet.Common.SshOperationTimeoutException: Session operation has timed out 
at Renci.SshNet.Session.WaitOnHandle(WaitHandle waitHandle, TimeSpan timeout) 
at Renci.SshNet.Session.Renci.SshNet.ISession.WaitOnHandle(WaitHandle waitHandle) 
at Renci.SshNet.Channels.Channel.WaitOnHandle(WaitHandle waitHandle) at Renci.SshNet.Channels.Channel.GetDataLengthThatCanBeSentInMessage(Int32 messageLength) 
at Renci.SshNet.Channels.Channel.SendMessage(ChannelDataMessage message) 
at Renci.SshNet.Channels.Channel.SendData(Byte[] data) 
at Renci.SshNet.SubsystemSession.SendData(Byte[] data) 
at Renci.SshNet.Sftp.SftpSession.SendMessage(SftpMessage sftpMessage) 
at Renci.SshNet.Sftp.SftpSession.SendRequest(SftpRequest request) 
at Renci.SshNet.Sftp.SftpSession.RequestWrite(Byte[] handle, UInt64 offset, Byte[] data, AutoResetEvent wait, Action`1 writeCompleted) 
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 Centauri.Management.UnixInterfaceManager.Transfer(String sourceFilePath, String destinationFilePath) in C:\XXXX\UnixInterfaceManager.cs:line 183 

New Post: Files not getting uploaded (possibly???)

$
0
0
I have a very basic routine which is shown below. Everything has been working swimmingly and all seems well. However, I keep having one particular client who is saying my files never make it onto the FTP site because they can't find them. Because all the other clients haven't had this issue, I "suggested" that the problem was on their end. However, today, I received an email from another client who indicated they couldn't find a file. So now I am concerned that something more is maybe going on here. I am not sure. I have sufficient logging in my application to show that a successful "upload path of execution" has occurred for all the missing files (i.e. no errors from the extensive error handling throughout the app and tons of successful logging messages).

I still think the problem might be on their side, but I want to be sure. I am looking for a way to log the interaction between the SftpClient and the server. Is there a way to accomplish this that I am not seeing in the library? What would be great is to be able to get a complete log of the FTP commands issued and the responses from the server. I am not seeing a way to do that. Any suggestions?

If there isn't a way to accomplish that, it would be great to build that into the library so that it could be logged by an app.

Thanks in advance for any help!
        private bool UploadToFtpSite(RunProfile profile, FileInfo x12File, String originalFileName)
        {

            if (profile.SkipUpload)
            {
                log.InfoFormat("Upload of file '{0}' skipped due to configuration item in the '{1}' profile.", x12File.FullName, profile.Description);
                //If the test mode is set to skip, we just return true stating it uploaded.
                return true;

            }


            FtpProfile ftpProfile = GetFtpProfile(profile, originalFileName);

            //only attempt to upload the file if there is a server name, username and password
            if (!String.IsNullOrWhiteSpace(ftpProfile.Server) && !String.IsNullOrWhiteSpace(ftpProfile.UserName) && !String.IsNullOrWhiteSpace(ftpProfile.Password))
            {

                using (SftpClient ftpClient = new SftpClient(ftpProfile.Server, ftpProfile.UserName, ftpProfile.Password))
                {

                    try
                    {
                        ftpClient.Connect();
                        
                        ftpClient.ChangeDirectory(ftpProfile.SubmissionPath);

                        using (var fileStream = new FileStream(x12File.FullName, FileMode.Open))
                        {
                            ftpClient.BufferSize = 4 * 1024; // bypass Payload error for large files
                            ftpClient.UploadFile(fileStream, x12File.Name);
                        }
                        
                        ftpClient.Disconnect();

                        return true;
                    }
                    catch (Exception e)
                    {
                        log.ErrorFormat(String.Format("Unable to upload file '{0}' to FTP server '{1}' from profile '{2}'", x12File.FullName, ftpProfile.Server, profile.Description), e);

                        return false;
                    }
                }

            }
            else
            {
                log.ErrorFormat("No valid ftp server was configured for {0} files in profile '{1}'.  If this is intentional, uncheck the 'Generate {0} file' option in the export profile in QCS.", ftpProfile.Claim ? "Claim" : "Encounter", profile.Description);
                return false;
            }
        }

New Post: Identifying that a command has finished (ShellStream)

$
0
0
Suppose I'm using ShellStream in the following way:
shellStream.Write("./interactive_command.sh\n"); // Command, that will ask me to prompt something
shellStream.Write("my first string\n");  // My first response to the prompt
shellStream.Write("my second string\n"); // My second response to the prompt
How do I know that the command './interactive_command.sh' has finished working and I can dispose ShellStream?
By the way, the command './interactive_command.sh' awaits the response silently, that is without any asking strings.

Created Unassigned: NullReferenceException after unexpected disconnection [2626]

$
0
0
I had an established connection when the client suddenly disconnected. This caused my application to crash with a NullReferenceException.

In the image one can see there's two possible scenarios this may happen if this._sessionErrorOccuredWaitHandle is null.

Version used: latest trunk (41298).

This may be related to #2591.

Patch Uploaded: #17245

$
0
0

RiJo has uploaded a patch.

Description:
Prevents NullReferenceException after unexpected disconnection.

Reviewed: 2014.4.6-beta2 (Feb 18, 2015)

$
0
0
Rated 5 Stars (out of 5) - Fantastic library, and well documented. Saved my skin since the .Net FtpWebRequest doesn't support SFTP or HTTP Proxies! I've used this in my File Upload handler to upload chunks of data via a Plupload GUI. Works like a charm.

New Post: Looking for help getting started

$
0
0
I'm brand new to the concept of FTP, SSH, SFTP, that sort of thing. While looking for a way to interact with SFTP in C#, I came across this library. After spending a few hours reading through the discussion boards and source code, it's become clear that this is way over my head. I'd appreciate any guidance at all to help me get my footing. I'm quite familiar with C#, but the extent of my FTP knowledge is using FileZilla to move files around.

Thanks!

New Post: Looking for help getting started

$
0
0
Not quite sure what you're looking for, but in thinking about some things that might cause confusion to someone just getting started I can think of the following grossly oversimplified comments:

FTP is an protocol for transferring files between two computers; it's plagued with problems in modern networks with firewalls, none of the protocol is encrypted (aka your username, password, and all data is sent over the network in plain old readable forms). There are millions of copies of the client code to support this protocol pretty much built-in to every meaningful system connected to the internet (similar to how http/s (web browsing) is built-in). More recently, mostly due to its inherent insecurity, but also due to the aggravation FTP causes firewalls, people are starting to actively refuse FTP, or are at least strongly encouraging people use better and more secure file transfer methods.

I'd say there are two primary leaders for the replacement, FTPS and SFTP.

First, FTPS (note the position of the 'S' in that identifier), is FTP with the Secure Sockets Layer (SSL) bolted on to it; it's the equivalent of HTTPS to HTTP. FTPS takes FTP and just wraps it an encrypted channel, that's it; encrypted FTP (just like HTTPS is simply encrypted HTTP). FTPS in my opinion, is simply more aggravating. It makes everything more complicated and harder to fix and by design prevents some of the "man-in-the-middle" NAT techniques that firewalls use to make FTP continue to work in the first place (an explanation of active mode versus passive mode FTP is beyond the scope of this comment. :))


The other is SFTP, a special case of implementing a protocol similar to FTP on top of the more general SSH protocol.
SSH (and it's children SFTP, SCP, et al.) under the hood is a different protocol from FTP entirely (though they can both support copying files).
See http://en.wikipedia.org/wiki/Secure_Shell


When dealing with SSH it's mainly happening on port 22, the server will first provide the connecting client a host-key (which can be used to validate that the server is actually the intended server; but this mechanism is not very well automated and usually just resorts to "ask the user if this 128bit hexadecimal string looks right"); then the client provides either username/password or private key based authentication credentials (or other mechanism if the client/server both support and choose it). SSH is extensible so that it can support many different types of encryption and authentication methods over time.

SSH's primary/original use was for opening a terminal prompt on the remote computer. It's main advantages were:
1) it was encrypted, authenticated, and supported various and extensible protocols
2) authentication could use either a username/password or a special private key file that the user had on their local (i.e. the initiating) computer
3) it additionally provided a basic means for authenticating that the server being connected to was actually the server intended (aka there was little chance there was a man-in-the-middle capturing the conversation/data stream).

In other words, it gave you an encrypted and more trustworthy way to "log in" to a text terminal on a remote computer very much like a direct VPN would.
Before long, people were using SSH to do specific tasks beyond just a text terminal, such as private VPNs between machines, file transfers, encrypted NAT/PORT redirection, remotely automated and secured jobs that didn't require some plaintext password be retrieved from a file somewhere (passwords that would get changed and the scripts have to be updated), and all manner of other nifty data transfer and automation tricks.


SSH has basically become an authenticated and encrypted swiss army knife of both TCP/IP and command level protocols depending on which one you need; and that doesn't necessarily require typing in a username and password every time it gets used to remotely connect. It also has some basic failsafes that prevent connection if any of the automated key mechanisms don't seem 100% kosher. So it is great for both automated, unattended tasks and for interactive log ins.

SSH's only main downside is that it is directly supported by pretty much every operating system/platform vendor on the planet except for Microsoft and that's what makes this SSH.Net project/library such a kick-ass and important piece of code and God bless all the people who are making it possible.

In fancy speak, create a connection to a remote server (an SshNet.SftpClient), using the connection information (SshNet.ConnectionInfo), giving it an Authentication Method (most likely a SshNet.PasswordAuthenticationMetod that takes a username and password). Or, if you want to be lazy about it and treat it just like FTP, use the SshNet.SftpClient constructor that takes the hostname, username, and password directly.

Once the SftpClient object has been instantiated with the appropriate ConnectionInfo; call its Connect() method.
Once the SftpClient is Connected, you can do lots of FTP like things; while SshNet supports lots of awesome Asynchronous callback methods which are great for GUIs (and tricky to implement properly so God bless them again!); it also supports several synchronous methods of interest like: DownloadFile("fileName", localFileStream), UploadFile(localFileStream, "fileName"), Get("fileName") (which gets detailed information about a file), and ListDirectory("path") which returns a List(Of SftpFile) object with all the files in "path" on the remote server.

Once you're done, call the SftpClient.Disconnect() method and Dispose() of the object (code with the "using" clause can skip these (especially dispose)).


Here's a brain dead example of synchronously downloading a file:
    public void Sftp_Download_File()
    {
        using (var sftp = new SftpClient(Resources.HOST, Resources.USERNAME, Resources.PASSWORD))
        {
            sftp.Connect();

            using (var fs = File.Create(@"C:\Temp\somefile.txt"))
            {
                sftp.DownloadFile("/somefile.txt", fs);
            }
            sftp.Disconnect();
        }
    }


So to sum up; whenever you can, using SFTP is way better than FTP (in my humble opinion); and its use should be preferred and encouraged. Since many folks have their brains melt when implementing protocols that use encryption we need a good library that works on the Microsoft platform and specifically with .Net (and that's this project).

Hope that helps get you started.

Cheers!
Mike

New Post: Exception on Disconnect "An established connection was aborted by the software in your host machine"

$
0
0
I'm getting a SocketException when calling Disconnect().

I dug through the code and can see what's happening:
In BaseClient.cs we have this:
    public void Disconnect()
    {
        ...

        OnDisconnecting(); // <--- This call actually ends up disposing of the SFTP sesssion
        StopKeepAliveTimer();
        if (Session != null) // <-- This object is not yet null, but the underlying session is disposed of
        {
            ...
            Session.Disconnect(); // <-- This call tries to send a message to the server that the client is causing the disconnect
            ...
        }
    }
It appears that there is a missing "Disconnect" call on the SftpClient.cs class or that the code which informs the remote server of the client disconnect reason needs to be moved to earlier in the code.

Feedback please.

Thanks,
Mike

Created Unassigned: Disconnect hangs for several minutes [2627]

$
0
0
Hi all,

when disconnecting the SftpClient it hangs for several minutes.
While investigating the issue, I found that the cause of this issue is situated in the SocketDisconnect method in Session.cs.


``` C#
partial void SocketDisconnect()
{
_socket.Disconnect(true);
}
```

Is there a reason why the Disconnect method is used with the parameter 'true', because the socket is never used again after the disconnect. It is even disposed after the disconnect.

Best regards

Created Unassigned: Keep alive signaling continues even after disconnection [2628]

$
0
0
I restarted (reboot in Linux) my ssh server which had an established connection with a keep-alive every 10s. Even after the disconnection, the following method was executed every 10s: BaseClient.SendKeepAliveMessage().

Seems like a call to BaseClient.StopKeepAliveTimer() is missing somewhere.
Viewing all 2955 articles
Browse latest View live


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