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

New Post: on cisco router no response after send Enable

$
0
0
class switchSshSession
    Class switchSshSession
        Inherits switchSession
        Private SSHPasswordConnection As Renci.SshNet.PasswordAuthenticationMethod
        Private SSHKeyboardInteractive As Renci.SshNet.KeyboardInteractiveAuthenticationMethod
        Private SSHConnectionInfo As Renci.SshNet.ConnectionInfo
        Private ClientSsh As Renci.SshNet.SshClient = Nothing
        Private SSHShell As Renci.SshNet.Shell = Nothing
        Private SSHStream As Renci.SshNet.ShellStream
        Private SSHreader As StreamReader
        Private SSHwriter As StreamWriter

        Public Sub New(scriptText As String, ResponseWait As Integer, ResponseRetries As Integer)
            ' The switchSshSession New call's base class New to fill ScriptSend and ScriptWait
            ' and performs the SSH session setup

            MyBase.New(scriptText, ResponseWait, ResponseRetries)
            ClientPort = 22

            Try
                ' if PasswordAuthentication is requested (demanded) by the switch, we can handle that
                SSHPasswordConnection = New Renci.SshNet.PasswordAuthenticationMethod(ClientUsername, ClientPassword)
                SSHKeyboardInteractive = New Renci.SshNet.KeyboardInteractiveAuthenticationMethod(ClientUsername)
                SSHConnectionInfo = New Renci.SshNet.ConnectionInfo(ClientIP, ClientPort, ClientUsername, SSHPasswordConnection, SSHKeyboardInteractive)

                AddHandler SSHKeyboardInteractive.AuthenticationPrompt, AddressOf SSHhandleKeyboardAuthentication

                ClientSsh = New Renci.SshNet.SshClient(SSHConnectionInfo)
                ClientSsh.ConnectionInfo.Timeout = TimeSpan.FromSeconds(10)
                ClientSsh.ConnectionInfo.RetryAttempts = 3
                ClientSsh.Connect()

                If ClientSsh.IsConnected = False Then
                    Throw New Exception("connection failed")
                    Exit Sub
                End If

                SSHStream = ClientSsh.CreateShellStream("xterm", 80, 24, 800, 600, 1024)
                SSHreader = New StreamReader(SSHStream)
                SSHwriter = New StreamWriter(SSHStream)
                SSHwriter.AutoFlush = True
                Thread.Sleep(ClientResponseWait)
                SSHreader.ReadToEnd()

            Catch ex As Exception
                sessionStatus = ex.Message & " connecting " & ClientIP & " port " & ClientPort & " (SSH)"
                ClientValid = False
            End Try

        End Sub
        Public Overloads Function ExecuteScript() As Boolean
            ' perform SSH i/o
            '
            ' In the While loop the commands in ScriptSend are send and responses in ScriptWait are 
            ' (substring) matched to the received response.
            ' SSHReadResult does the actual reading.
            ' The ClientResponse is build up as we go along, replacing passwords with *******

            ExecuteScript = False

            Dim sendString As String = ""
            Dim waitString As String = ""
            Dim receivedString As String = ""
            Dim PasswordSkip As Boolean = False
            sessionIOindex = 3 ' ssh offset 3: 0 = ip, 1 = username, 2 = password
            Try

                While sessionIOindex < ScriptSend.Length
                    sendString = ScriptSend(sessionIOindex)
                    waitString = ScriptWait(sessionIOindex)

                    SSHStream.Write(sendString & vbCr)          ' send command
                    receivedString = SSHReadResult(waitString)  ' read result

                    If receivedString.IndexOf(waitString, 0, receivedString.Length, StringComparison.CurrentCultureIgnoreCase) < 0 Then
                        Throw New Exception("received: '" & receivedString & "' waiting for: '" & waitString & "'")
                    End If

                    If PasswordSkip Then
                        ClientResponse += "*******"
                    Else
                        ClientResponse += receivedString
                    End If
                    ClientResponse += Environment.NewLine

                    PasswordSkip = False
                    If receivedString.IndexOf("password", 0, receivedString.Length, StringComparison.CurrentCultureIgnoreCase) >= 0 Then
                        PasswordSkip = True
                    End If
                    sessionIOindex += 1
                End While
                ExecuteScript = True

            Catch ex As Exception
                sessionStatus = ex.Message & Environment.NewLine & "send [ " & sendString & _
                    " ] to " & ClientIP & " (SSH), expecting response to contain [ " & waitString & " ] (script-index " & sessionIOindex * 2 & ")"
                ExecuteScript = False
            End Try
        End Function
        Private Sub SSHhandleKeyboardAuthentication(sender As Object, e As Renci.SshNet.Common.AuthenticationPromptEventArgs)
            For Each prompt As Renci.SshNet.Common.AuthenticationPrompt In e.Prompts
                If prompt.Request.Equals("Password: ", StringComparison.InvariantCultureIgnoreCase) Then
                    prompt.Response = ClientPassword
                End If
            Next
        End Sub
        Private Function SSHReadResult(Expected As String) As String
            ' Read the result from SSHreader until Expected is read.
            ' Commands issued to the switch may require some processing. Not all data may be available at once, so give em some slack.
            ' We asume the command send to allways be received by the switch
            Dim strRead As String = ""
            Dim retries As Integer = 0
            Try
                Thread.Sleep(ClientResponseWait)        ' give IOS a first change to form the response
                strRead = SSHreader.ReadToEnd

                While retries < ClientResponseRetries
                    If strRead.IndexOf(Expected, 0, strRead.Length, StringComparison.CurrentCultureIgnoreCase) < 0 Then
                        retries += 1
                        Thread.Sleep(ClientResponseWait)
                        If SSHStream.DataAvailable Then
                            strRead += SSHreader.ReadToEnd   ' append to data already received
                        End If
                    Else
                        Exit While
                    End If
                End While

                Return (strRead)

            Catch ex As Exception
                Return (Nothing)
            End Try
        End Function
        Public Overloads Sub Dispose()
            MyBase.Dispose()
            On Error Resume Next
            SSHreader.Close()
            SSHreader.Dispose()
            SSHwriter.Close()
            SSHwriter.Dispose()
            SSHShell.Dispose()
            Err.Clear()
        End Sub
    End Class
Many thanks to the Renci SSH.NET developers!

Regards, Paul

New Post: Invoke-SsshCommand password problem

$
0
0
Hi,
I trying to execute a command using Invoke-SshCommand. While executing a command with sudo, its giving error bcz password not passed for sudo. So please anyone help me on how to deal with.

ex:
New-SshSession -ComputerName "XYZ" -UserName "xyz" -PassWord "*******"
Invoke-SsCommand -CompterName "XYZ" -Command "Sudo mkdir test"
Remove-SshSession
error is: had an error: sudo: no tty present and no askpass program specified

So the directory was not created. I manually checked the same command, asking for sudo password.

Thanks,
Bhaskar.

New Post: VB.NET Framework 3.5 and Renci ssh - keep session open

$
0
0
Hi everyone,

I'm using Renci SSH within my vb.net project and wondering how I can pass multiple commands and keep the session open.

I'm just testing things at the moment, but I'd like to navigate to a directory "cd /home/temp/" with one command, then after that has run, do something like "ls -l" and provide the results in a label or text box.

My code at present is as follows...
    Private Sub btnSSHTest_Click(sender As Object, e As EventArgs) Handles btnSSHTest.Click
        'Create the objects needed to make the connection'

        Dim connInfo As New Renci.SshNet.PasswordConnectionInfo(txtConnectionNode.Text, txtboxUsername.Text, txtboxPassword.Text)

        Using client As New Renci.SshNet.SshClient(connInfo)
            client.Connect()

            Dim cmd As Renci.SshNet.SshCommand
            Dim result As String
            Dim result2 As String

            cmd = client.CreateCommand("cd /home/temp/")
            result = cmd.Execute
            cmd = client.CreateCommand("ls -l")
            cmd.CommandTimeout = TimeSpan.FromSeconds(10)
            result = cmd.Execute
            result2 = cmd.Error
            TextBox1.Text = cmd.ExitStatus

            If String.IsNullOrEmpty(result2) Then
                TextBox1.Text = result2
            End If

            TextBox1.Text = result

            client.Disconnect()
        End Using


    End Sub
But the ls -l command just doesn't recognise that the cd /home/temp/ command has been run. Am I missing something? Does the SSH not work this way?

New Post: VB.NET Framework 3.5 and Renci ssh - keep session open

Created Unassigned: File corruption on download [1951]

$
0
0
I attached sources to test the bug. The bug occurred in last version from SVN. Last official release of 2013 year works fine.

Created Unassigned: Exists function returns always true for any file [1952]

$
0
0
See attached test source. Some old version of ssh.net worked fine.

New Post: Slow failure reading non-existing file using SCP

$
0
0
Hi,

Just tried to reproduce it and it fails fast:
            var start = DateTime.Now;

            try
            {
                var scp = new ScpClient(res.host, int.Parse(res.port), res.user, res.password);
                scp.Connect();
                var file = new FileStream("bla", FileMode.OpenOrCreate, FileAccess.Write);
                scp.Download("bla", file);
                scp.Disconnect();
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }
            finally
            {
                var end = DateTime.Now;
                Console.WriteLine("Time: " + (end - start));
            }

            Console.ReadLine();
=>
scp: bla: No such file or directory
Time: 00:00:00.5669936
Sounds like a problem, not a known/wanted behaviour.
Do you have other servers to test?

Commented Unassigned: 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 **

I am facing the same issue. When I Check whether file or directory exists or not, it always returns true even that file or directory does not exist.

Though it is working fine on Linux server.


New Post: sftp client 'Exists' method returns true always

$
0
0
I am using SSH.NET library which is working perfectly on LINUX SFTP server. But I used the same code to check on Windows SFTP but it is not working as expected.

Issue is that when I check whether Directory or File exists or not using sftpClient.Exist(Path) method, it always returns true even that file or directory does not exist.

Below is the code I am using :
this.sftpClient = new SftpClient([HOST], [PORT], [USER_NAME], [PASSWORD]);
this.sftpClient.OperationTimeout = new TimeSpan(0, 0, 0, 10);
this.sftpClient.ConnectionInfo.Timeout = new TimeSpan(0, 0, 10, 0);
this.ConnectToServer();

var pathToCheck = [PATH];

// Exists always return true
if (!this.sftpClient.Exists(pathToCheck))
{
    this.sftpClient.CreateDirectory(pathToCheck);
}

Commented Unassigned: File corruption on download [1951]

$
0
0
I attached sources to test the bug. The bug occurred in last version from SVN. Last official release of 2013 year works fine.
Comments: ** Comment from web user: drieseng **

I only had time to take a quick look, but the issue appears to be specific to this ssh server.
I can even reproduce the issue using WinSCP.

Commented Unassigned: 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: da_rinkes **

I can reproduce it with OpenSSH 6.4 on OpenBSD, but with OpenSSH 6.2 on Ubuntu 13.10 Exists() works
as expected.

This issue depends on ssh-server version or OS?
Can you test some more, it might help the devs to reproduce/fix the issue.

Commented Unassigned: 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: trurl123 **

I cannot fix SFTP server. Google owns it. See attached sources. It contains test account for this.

Commented Unassigned: File corruption on download [1951]

$
0
0
I attached sources to test the bug. The bug occurred in last version from SVN. Last official release of 2013 year works fine.
Comments: ** Comment from web user: trurl123 **

Yes, WinSCP has bug too. Use FileZilla.

Commented Unassigned: 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 **

@da_rinkes : my application has been hosted on Windows server and it connects to the Windows SFTP server provided by [Cerberus](http://www.cerberusftp.com/)

Commented Unassigned: 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: da_rinkes **

hehe, i didn't expect you to fix the server :)
I just think it would be nice if this issue can be nailed down to a specific server version or OS

It's quite strange that I can reproduce it with OpenBSD, but not with ubuntu.


Commented Unassigned: 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: drieseng **

The problem lies with the use of SSH_FXP_REALPATH.
The spec has not always been clear on how the server should respond when the specified path is not present on the server:

SSH 1 to 4: No mention of how the server should respond if the path is not present on the server.
SSH 5: The server SHOULD fail the request if the path is not present on the server.
SSH 6:
Draft 06: The server SHOULD fail the request if the path is not present on the server.
Draft 07 to 13: The server MUST NOT fail the request if the path does not exist...

Note that SSH 6 (draft 06 and forward) allows for more control options, but we currently only support up to v3.

Commented Unassigned: 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: drieseng **

I think I'll modify Exists to use SSH_FXP_LSTAT, and only return false when the server responds with SSH_FX_NO_SUCH_FILE.

Any thoughts ?

Note this issue is a duplicate of issue #1696 and #1574.

Commented Unassigned: various System.ObjectDisposedException [1944]

$
0
0
during a long connection I get following exceptions:

```
System.ObjectDisposedException: Das SafeHandle wurde geschlossen.
bei Renci.SshNet.Session.WaitHandle(WaitHandle waitHandle) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Session.cs:Zeile 642.
bei Renci.SshNet.Channels.Channel.WaitHandle(WaitHandle waitHandle) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Channels\Channel.cs:Zeile 496.
bei Renci.SshNet.Channels.ChannelSession.Open() in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Channels\ChannelSession.cs:Zeile 52.
bei Renci.SshNet.ShellStream..ctor(Session session, String terminalName, UInt32 columns, UInt32 rows, UInt32 width, UInt32 height, Int32 maxLines, IDictionary`2 terminalModeValues) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\ShellStream.cs:Zeile 73.
bei Renci.SshNet.SshClient.CreateShellStream(String terminalName, UInt32 columns, UInt32 rows, UInt32 width, UInt32 height, Int32 bufferSize, IDictionary`2 terminalModeValues) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\SshClient.cs:Zeile 384.
bei Renci.SshNet.SshClient.CreateShellStream(String terminalName, UInt32 columns, UInt32 rows, UInt32 width, UInt32 height, Int32 bufferSize) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\SshClient.cs:Zeile 366.
```

and

```
System.ObjectDisposedException: Das SafeHandle wurde geschlossen.
bei System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean& success)
bei Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle)
bei System.Threading.EventWaitHandle.Set()
bei Renci.SshNet.ShellStream.Channel_DataReceived(Object sender, ChannelDataEventArgs e) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\ShellStream.cs:Zeile 739.
bei Renci.SshNet.Channels.Channel.OnData(Byte[] data) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Channels\Channel.cs:Zeile 289.
bei Renci.SshNet.Channels.Channel.OnChannelData(Object sender, MessageEventArgs`1 e) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Channels\Channel.cs:Zeile 590.
bei System.EventHandler`1.Invoke(Object sender, TEventArgs e)
bei Renci.SshNet.Session.OnChannelDataReceived(ChannelDataMessage message) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Session.cs:Zeile 1392.
bei Renci.SshNet.Session.HandleMessage(ChannelDataMessage message) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Session.cs:Zeile 1034.
bei CallSite.Target(Closure , CallSite , Session , Object )
bei Renci.SshNet.Session.HandleMessageCore(Message message) in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Session.NET40.cs:Zeile 20.
bei Renci.SshNet.Session.MessageListener() in c:\Users\srinkes\Desktop\Projects\XXX\Renci.SshNet\Session.cs:Zeile 1589.
```

The application opens a ssh connection and opens/parses a ShellStream every 10 seconds.
IsConnected stays true.

I currently can't test the current beta since it has issues with closing the channel after
disposing the ShellStream.

No errors or unusual log entries on the server side.
Comments: ** Comment from web user: drieseng **

I've fixed the IsConnected issue locally, I had to move to async socket receive socket (while adding locking to synchronize between receive and checking whether the socket is connected).

I'll need to perform some more tests before I can (and want to) commit these changes.

Commented Unassigned: 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: da_rinkes **

Does Exists() still work on directories if SSH_FXP_LSTAT is used instead?

The RFC also mentions:
If an error occurs, the server may also respond with SSH_FXP_STATUS.

Is it the case that, the "may" is causing the troubles here?

Commented Unassigned: 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: da_rinkes **

drieseng: Looks good with RequestLStat instead of RequestRealPath.

Don't forget to check nullOnError before throwing a exception :)

Viewing all 2955 articles
Browse latest View live


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