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

New Post: Shell functionlity

$
0
0
supermanSC wrote:
I'm trying to get this working on a Cisco 65xx switch, and can't seem to get past the enable password prompt.  Oleg, if you're not familiar with Cisco, once you connect using the primary username/password, you need to issue the "enable" command to gain some elevated access levels. Once that's issued, the router will respond with a "Password: " prompt, which requires a password to be entered.  For whatever reason, if I read to the end of the stream prior to entering a password, it's like something is either being entered, or a linefeed is sent across, in which case the Cisco replies with "Bad Password".  Here's the small routine I'm testing with:     Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click        Using client = New SshClient("1.1.1.1", "username", "password")            client.Connect()            Using sshStream = client.CreateShellStream("dumb", 80, 24, 800, 600, 1024)                Dim reader = New StreamReader(sshStream)                Dim writer = New StreamWriter(sshStream)                writer.AutoFlush = True                While sshStream.Length = 0                    Thread.Sleep(500)                End While                Response.Write(reader.ReadToEnd)                writer.WriteLine("enable")                While sshStream.Length = 0                    Thread.Sleep(500)                End While                Response.Write(reader.ReadToEnd.ToString.Replace(vbCrLf, "<BR>"))            End Using            client.Disconnect()        End Using    End Sub   ----   Here's what's returned: test_6506>enablePassword: <--------------- I need to send a password here, yet something is being automatically sent in it's place.% Access deniedtest_6506>
I banged my head on this for a couple of days. I was also using the library to manage cisco routers. SharpSSH worked perfectly fine, but I couldn't get the expect function work correctly in SSH.NET.

After re-reading this thread multiple times, this post got me thinking that there had to be something different between SharpSSH's writeline method and SSH.NET's.

After looking at both library's source I found that SharpSSH is only sending a \r where SSH.NET is sending \r\n. The Cisco's are interpreting the \r\n as a double enter key press.

I changed my code to use write and appended the \r and everything works like a champ.

New Post: SFTP Keyboard Interactive Authentication

$
0
0
Hi,

I'm trying to get files via sftp, but I can figure out which classes I need to use.
At first I tried to connect by simply using an SftpClient object, like shown in an example I found

    using (var sftp = new SftpClient(host, username, password))
    {
        sftp.Connect();

        using (var file = File.OpenRead(localFileName))
        {
            sftp.UploadFile(remoteFileName, file);
        }https://sshnet.codeplex.com/discussions/create#

        sftp.Disconnect();
    }
but sftp.Connect(); throws an SSHAuthenticationException;

Connecting to the server via putty i recognized it uses keyboard-interactive authentication and tried to creat the SftpClient like this:
            KeyboardInteractiveConnectionInfo conInfo = new KeyboardInteractiveConnectionInfo(host, port, username);

            SftpClient client = new SftpClient(conInfo);
            client.Connect();
Which throws an ArgumentNullException.

Whats the right way to creat an SftpClient connection?

Created Unassigned: Remove Line Feed from WriteLine method in Shellstream Class [1584]

$
0
0
When working with the expect method, it was discovered the WriteLine was sending an linefeed after a carriage return. This was throwing some SSH implementations off because the linefeed is being interpreted as a second carriage return.

I'm suggesting that:

var commandText = string.Format("{0}{1}", line, "\r\n");

be replaced with

var commandText = string.Format("{0}{1}", line, "\r");

Commented Issue: Remote File exists not working [1574]

$
0
0
I've tried to use sftp.Exists(String) do not work for files. Already tested for file and for directory. Directory work well, but files are not recognized.
Comments: ** Comment from web user: deanis **

I find that with the latest version (at least) sftp.Exists(string) always returns true. That's too bad, because it just caused me to mistakenly delete 900MB of data that my code thought was a duplicate. When I reverted to an earlier version from 2012, Exists() reliably returns true or false.

New Post: Unable to show result if it has more than a line.

$
0
0
Hi,

First of all thanks for developing such a great library for SSH.

I am facing a problem whereby I am not able to show the result if I execute command such as "ls", which will return result with more than a line. The result would be blank even though the ExitStatus is 0.
However, it works perfectly if the command (i.e. "pwd" or "date") only returns one line.

Below is the code snippet which I am using currently:
using (SshClient client = new SshClient("host", "username", "password"))
{
  client.Connect();

  SshCommand cmd = client.CreateCommand("ls"); //works perfectly if substitutes "ls" with "pwd" or "date" which will only return result with one line.

  cmd.Execute();

  string result = cmd.Result;
  Console.WriteLine(result);

  client.Disconnect();
}
I would very appreciate if anyone of you could enlighten me so that the problem of displaying multiple line of result could be solved.

Thanks in advance. :)

Commented Issue: Remote File exists not working [1574]

$
0
0
I've tried to use sftp.Exists(String) do not work for files. Already tested for file and for directory. Directory work well, but files are not recognized.
Comments: ** Comment from web user: ronnieoverby **

Please fix this.

New Post: No strong naming?

$
0
0
Is it possible to enable strong naming for this library in the NuGet package?

New Post: "Session operation has timed out" error?

$
0
0
Hi,

I am trying to use this library to upload a file via SFTP, and it connects fine and even puts an empty file onto the SFTP server, but then it just sits there and eventually times out with a session operation has timed out exception. The code is basically as follows:
            var uri = new Uri(remoteUri);
            if (uri.Scheme == "sftp") {
                // Upload the file using sftp over SSH
                var host = uri.Host;
                var userInfo = uri.UserInfo.Split(':');
                if (userInfo.Length > 1) {
                    var username = userInfo[0];
                    var password = userInfo[1];
                    using (var sftp = new SftpClient(host, username, password)) {
                        sftp.Connect();
                        using (var file = File.OpenRead(localFile)) {
                            sftp.UploadFile(file, uri.LocalPath);
                        }
                        sftp.Disconnect();
                    }
                } else {
                    throw new ArgumentException("Unable to parse username and password from URI");
                }
            }
Any idea what would cause this? I have debugged into a debug build of the source code (built with VS2012) and it gets stuck as soon as it attempts to send any data?

New Post: "Session operation has timed out" error?

$
0
0
Any suggestions on what to try here? This same code works perfectly to a windows server using WinSSHD and also to a Linux server. But it fails when connecting to the server we need to connect to (which I have no control over). The server they are using is EFT Server 6.1.0 Build 10.30.2009.48, if that makes any difference?

New Post: "Session operation has timed out" error?

$
0
0
Aha, finally found the issue! The core problem is the server we are connecting to is really, REALLY slow! I have no idea why it is so slow, but with the default buffer size of 16K, it times out trying to send data to the server. I changed it to a 1K buffer size and it worked just fine.

So, in reality I don't want to change the default buffer size, but what I do need to change is the timeout. What timeout is happening during uploads that would cause problems if the SFTP server is really slow? I plan to debug the code a bit and see if I can spot it. Worst case I can work out what buffer size works with this server and force that, but in reality the proper fix is to change the library so it handles this situation correctly ...

New Post: "Session operation has timed out" error?

$
0
0
Hmm, the connection we are using to this server appear to be a T1, as it runs about 130KB per second. So it makes no sense that a 16K buffer transfer would cause a timeout? I think I will try different buffer sizes, but perhaps this particular server has issues with 16K buffers?

New Post: "Session operation has timed out" error?

$
0
0
Pretty sure at this point there is something totally screwy with EFT Server 6.1.0. Using FireFTP to upload files to their server takes about 1:20 to upload 6MB of data. When I change the buffer size in SSH.NET to 8K, it uploaded the exact same file in 6.5 seconds! I downloaded it again and verified it was correct so clearly something is off in their SSH server causing these issues. So I am not sure there is anything we need to fix here. I have asked them to upgrade to the latest 6.5.x release to see if that resolves the issues we are seeing as well. But for now I will stick to an 8KB buffer.

Created Unassigned: Random NullReferenceException during SFTP disconnect [1587]

$
0
0
Hi,

I have a windows service which synchronizes through SFTP with custom specified intervals, it is installed on 3 machines with 3 different operating systems. On one machine an exception occurs randomly at the disconnect event and I cannot figure out why. On the other machines the problem occurred only once, on this particular machine it occurs every day, sometimes multiple times daily. The application is multithreaded, more than one synchronization jobs can be executed simultaneously. The exception happens only at disconnect, not during upload/download, and always on "empty" sessions where the thread just connects, retrieves a filelist and then disconnects when it notices that there is currently nothing to synchronize.

The exception is a NullReferenceException, message from the log:

```
[2013.05.27. 1:28:45] UNHANDLED EXCEPTION! Message: Az objektumhivatkozás nincs beállítva semmilyen objektumpéldányra. - Stack trace: a következő helyen: Renci.SshNet.Sftp.SubsystemSession.RaiseError(Exception error)
a következő helyen: Renci.SshNet.Sftp.SubsystemSession.Session_ErrorOccured(Object sender, ExceptionEventArgs e)
a következő helyen: System.EventHandler`1.Invoke(Object sender, TEventArgs e)
a következő helyen: Renci.SshNet.Session.RaiseError(Exception exp)
a következő helyen: Renci.SshNet.Session.MessageListener()
a következő helyen: Renci.SshNet.Session.<Connect>b__4()
a következő helyen: Renci.SshNet.Session.<>c__DisplayClass3d.<ExecuteThread>b__3c(Object o)
a következő helyen: System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
a következő helyen: System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
a következő helyen: System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
a következő helyen: System.Threading.ThreadPoolWorkQueue.Dispatch()
a következő helyen: System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
```

The code (most important part):

```
private SftpClient sftpClient = null;

......................................

public void Synchronize( Object stateObject )
{
//................
try
{
sftpClient = new SftpClient( Address, Port, Username, Password ); // don't want to use "using" because of the finally block
try
{
Log( "Connecting to server" );
sftpClient.Connect();
}
catch (Exception ex)
{
Log( "Error while connecting: " + ex.Message );
return; // finally block still will run
}
// ............. filelist, upload/download (this is a large block), everything in try/catch
}
finally
{
if (sftpClient != null)
{
if (sftpClient.IsConnected)
{
Log( "Disconnecting from server" );
sftpClient.Disconnect();
}
sftpClient.Dispose();
}
}
```

I attached the complete log file, please check it out, I don't know why the error is coming and how to avoid it. (Besides the "solution" to enclose the two method calls in the finally block in a try/catch block itself, which isn't too pretty.) Please help if you can.

Thank you, best regards,
Dester

New Post: Cannot make SshClient stop echo-ing

$
0
0
Hi,

When I setup a connection to an SSH Server I see the commands I send later echoed back to me. How can I stop getting my commands echo'ed back to me?

I use the following code, with variations....
        AuthenticationMethod am = new PasswordAuthenticationMethod(Credentials.UserName, Credentials.Password);
        ConnectionInfo connectionInfo = new ConnectionInfo( RemoteHostIP, Credentials.UserName, new AuthenticationMethod[] { am });

        _sshClient = new SshClient(connectionInfo);
        _sshClient.Connect();

        Dictionary<TerminalModes, uint> terminalModes = new Dictionary<TerminalModes,uint>();
        //terminalModes.Add(TerminalModes.ECHO, 0);
        //terminalModes.Add(TerminalModes.ONOCR, 1);
        _sshStream = _sshClient.CreateShellStream("xterm", 0, 0, 0, 0, 1024, null);//terminalModes);
I tried several terminalModes but without succes.

Please advise...

Regards,
Erik

New Post: SSH.NET for Microsoft.Net 4.0

$
0
0
Hello,

I would like to know can we implement SSH.NET library in the application without storing certificate in the code?


Best Regards,
Chetan Navale | chetan.navale@hotmail.co.in | +91-9373364792

New Post: Coding Problem

$
0
0
Hello Friend I am making a GUI for my vpn in visual basic and I am getting a problem when I am using
("perl something.pl" + somehting + something1 + something2)
but when I am using
("perl something.pl something1value something2value")
everything is working fine any solution please

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim IP As String = "xxx.xxx.xxx.xxx"
Dim Username As String = "root"
Dim Password As String = "mypassword"
Dim cmd As Renci.SshNet.SshCommand
Dim connInfo As New Renci.SshNet.PasswordConnectionInfo(IP, Username, Password)
Dim sshClient As New Renci.SshNet.SshClient(connInfo)
Dim something As String = TextBox1.Text
Dim something1 As String = TextBox2.Text
Dim something2 As String = TextBox3.Text
sshClient.Connect()
cmd = sshClient.RunCommand("perl something.pl" +something + something1 + something2)
Label1.Text = cmd.Result
End Sub
End Class

New Post: Channel sessions not cleaning up (Avoiding Memory Leaks)

$
0
0
I have an application which requires very long term execution. It creates a series of SshCommand objects (Each with a specific command) then executes those (using command.execute()) once every few seconds for multiple weeks. The string results are used to populate various parsers and GUI elements.

I have not been able to isolate the reasons, but what I see are millions of left over ChannelSession objects resulting in a system crash (Out of memory).

I suspect I simply am not using the library correctly since there's no mention of this in recent discussions. Is there a good reference example of how to use the library to perform long term polling (Via SshCommand)?

Generally, my technique is:
  • Create a ConnectionInfo object conn
  • Create a SshClient(conn) object client
  • Call client.Connect()
  • Add SshCommand (s) to client using client.CreateCommand()
  • Periodically execute the SshCommands using command.Execute()
  • When the program is done, call client.Disconnect() and client.Dispose()
In WinDbg.exe, I see persistent ChannelSession objects which should have been garbage collected. Included with these are many events such as AutoReset and ManualReset events.

If my technique is correct, why is ChannelSession not being garbage colledted after each Execute()? The EndExecute() method looks like it should be Closing the channel:
        public string EndExecute(IAsyncResult asyncResult)
        {
            if (this._asyncResult == asyncResult && this._asyncResult != null)
            {
                lock (this._endExecuteLock)
                {
                    if (this._asyncResult != null)
                    {
                        //  Make sure that operation completed if not wait for it to finish
                        this.WaitHandle(this._asyncResult.AsyncWaitHandle);

                        if (this._channel.IsOpen)
                        {
                            this._channel.SendEof();

                            this._channel.Close();
                        }

                        this._channel = null;

                        this._asyncResult = null;

                        return this.Result;
                    }
                }
            }
Thanks,

Robert

New Post: SSH through Proxy Problem

$
0
0
Hello guys,

im trying to connect through a proxy to my SSH server but i get an exception: "Socket read operation has timed out". In the Java Console i can see that it is connecting to Proxy but cant get connection to server. I tryed to connect with PuTTY using the same configuration and it worked fine. I also tryed another lib "Chilkat" and it worked fine (without KeyAuthentification) too but you have to buy a license to unlock the trial version and other libs dont support proxy functionality..... :(

the code im using:

ConnectionInfo connectionInfo = new ConnectionInfo("xx.xx.xx.xx", 22, "username", ProxyTypes.Http, "127.0.0.1", 18080, "", "", new PasswordAuthenticationMethod("username", "password"));
        try
        {
             using (var ssh = new SshClient(connectionInfo))
            {
                ssh.Connect();

                ssh.RunCommand("ls -l");

                ssh.Disconnect();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine();
        }
Are there some more ssh-libs that support proxy and are free maybe? or am i doing something wrong with ssh.net (maybe a flag that need to be set or something)?

Thanks in advance

killikax

New Post: No such File or Directory

$
0
0
The issues with this code snippet is that a user might not have the rights to do anything but scp.
Calling the "cd" command will only raise an error.
For my purposes, I created an additional method in ScpClient that assumes the directory structure already exists on the remote host.
That way, I can simply copy files over without worrying about any of this. And since it does not split the string, the leading / is not lost in the process (which ultimately leads to the observed behaviour of copying into one's home folder).
This is, no doubt, only a workaround, but it works for me.
        /// <summary>
        /// Uploads the specified stream to the remote host.
        /// This method assumes that the remote directory structure already exists.
        /// </summary>
        /// <param name="source">Stream to upload.</param>
        /// <param name="path">Remote host file name.</param>
        public void UploadFile(Stream source, string path)
        {
          using (var input = new PipeStream())
            using (var channel = this.Session.CreateChannel<ChannelSession>())
            {
                channel.DataReceived += delegate(object sender, Common.ChannelDataEventArgs e)
                {
                    input.Write(e.Data, 0, e.Data.Length);
                    input.Flush();
                };

                channel.Open();

                channel.SendExecRequest(string.Format("scp -rt \"{0}\"", path));
                this.CheckReturnCode(input);

                this.InternalUpload(channel, input, source, path);
                this.CheckReturnCode(input);

                channel.Close();
            }
        }

New Post: Channel sessions not cleaning up (Avoiding Memory Leaks)

$
0
0
The code in SshCommand 2013.4.7 (EndExecute):
        public string EndExecute(IAsyncResult asyncResult)
        {
            if (this._asyncResult == asyncResult && this._asyncResult != null)
            {
                lock (this._endExecuteLock)
                {
                    if (this._asyncResult != null)
                    {
                        //  Make sure that operation completed if not wait for it to finish
                        this.WaitHandle(this._asyncResult.AsyncWaitHandle);

                        if (this._channel.IsOpen)
                        {
                            this._channel.SendEof();

                            this._channel.Close();
                        }

                        this._channel = null;
                        this._asyncResult = null;

                        return this.Result;
                    }
                }
            }

            throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
        }
If _channel is set to null here, it appears _channel will not be properly disposed (Because SshCommand's Dispose() checks for _channel being null).

Additionally _asyncResult.AsyncWaitHandle.Dispose() isn't being called. I don't know if that will be properly GC'd (The web discussions seem a bit conflicted on this topic).

I'm going to try the following code:
        public string EndExecute(IAsyncResult asyncResult)
        {
            if (this._asyncResult == asyncResult && this._asyncResult != null)
            {
                lock (this._endExecuteLock)
                {
                    if (this._asyncResult != null)
                    {
                        //  Make sure that operation completed if not wait for it to finish
                        this.WaitHandle(this._asyncResult.AsyncWaitHandle);

                        if (this._channel.IsOpen)
                        {
                            this._channel.SendEof();

                            this._channel.Close();
                        }

                        // Dispose managed ResourceMessages.
                        if (this._channel != null)
                        {
                            this._channel.DataReceived -= Channel_DataReceived;
                            this._channel.ExtendedDataReceived -= Channel_ExtendedDataReceived;
                            this._channel.RequestReceived -= Channel_RequestReceived;
                            this._channel.Closed -= Channel_Closed;

                            this._channel.Dispose();
                            this._channel = null;
                        }

                        this._asyncResult.AsyncWaitHandle.Dispose();
                        this._asyncResult = null;

                        return this.Result;
                    }
                }
            }

            throw new ArgumentException("Either the IAsyncResult object did not come from the corresponding async method on this type, or EndExecute was called multiple times with the same IAsyncResult.");
        }
I'll write back with my results.
Viewing all 2955 articles
Browse latest View live


Latest Images

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