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

New Post: Timeout establishing SSH sessions

$
0
0
I'm still trying to determine exactly where the code is hanging. I've added some debug code but since then I haven't run in to the issue.
I'm running into this issue on a certain SSH accessible management devices on my network so there is nothing that would be publicly accessible. Fortunately we are gradually phasing these devices out but I'll have to deal with them for at least another year before they are all gone.

New Post: Timeout establishing SSH sessions

$
0
0
Hi Jim

The code is very simple, I can connect using ssh but when I execute a command I get the following error:-

Enter-SshSession : Exception calling "RunCommand" with "1" argument(s): "Session operation has timed out"

Code below:-

New-SshSession -ComputerName <myipaddress> -Username 'myservername\username' -Password 'mypassword' -port 22
Enter-SshSession -ComputerName <myipaddress>

try{
$results = Invoke-SshCommand -Command 'mkdir c:\test' -ComputerName <myipaddress>
}
catch {
Write-host $($Error[0].Exception.Message)
}
finally
{
Remove-SshSession -RemoveAll
Get-SshSession
}
$results = Invoke-SshCommand -Command

New Post: Unable to read documentation

New Post: Timeout establishing SSH sessions

$
0
0
Can you provide the full stack trace (instead of just Exception.Message) ?
Modifying this:

Write-host $($Error[0].Exception.Message)

into this should do the trick:

Write-host $($Error[0].Exception)

Thanks!

New Post: Unable to read documentation

$
0
0

Hi drieseng,

Thank you, I did unlock its working fine.

Earlier I read “unlock” but it is after you right click sshnet.chm>click properties> unlock [at bottom].

But I was confused, now I got that.

-Avinash

New Post: PasswordConnectionInfo Timeout doesn't appear to be working in Powershell

$
0
0
Hi,

I have the following PowerShell script that I'm testing (using either 2014.4.6-beta1 or 2013.4.7). When I put in a bogus IP Address for a switch, the timeout always seems to be about 20-25 seconds, even though I have set it to 60 seconds. If I set the timeout to 5 seconds, it times within 5 seconds as expected. It's only when you try end extend the timeout period that it seems to ignore it.

Does anyone have any idea?

#------------------------------------------------------------------------------------
# Define the Read and Write Stream functions for the script to be used
#------------------------------------------------------------------------------------
function ReadStream($reader)
{
    $line = $reader.ReadLine();
    while ($line -ne $null)
    {
        $line
        $line = $reader.ReadLine()
    }
}

function WriteStream($cmd, $writer, $stream)
{
    $writer.WriteLine($cmd)
    while ($stream.Length -eq 0)
    {
        start-sleep -milliseconds 500
    }
}


#------------------------------------------------------------------------------------
# Define Cmdlet to SSH to client and execute custom script to change account password
#------------------------------------------------------------------------------------
function Set-CiscoHostPassword {
[CmdletBinding()]
    param(
        [String]$HostName,
        [int]$Port,
        [String]$UserName,
        [String]$OldPassword,
        [String]$NewPassword
    )

#Script to be called once a SSH session has been established. Add one command per line.
$Script = @"
    config t
    username $UserName privilege 15 secret $NewPassword
    exit
    wr mem
    exit
"@

    try {
        #Make a connection to the host
        Add-Type -Path "[RenciSSHMetPath]\Renci.SshNet.dll" #Include SSH.NET Assembly
        $connectionInfo = New-Object Renci.SshNet.PasswordConnectionInfo($HostName, $Port, $UserName, $OldPassword)
        $connectionInfo.Timeout = New-TimeSpan -Seconds 60  
        
        $sshclient = New-Object Renci.SshNet.SshClient($connectionInfo)
        $sshclient.Connect()
        $sshclient.SendKeepAlive()

        if ($sshclient.IsConnected)
        {
            #Now that we are connected, attempt to execute the script above
            $stream = $sshclient.CreateShellStream("ssh_stream", 80, 24, 800, 600, 1024)
            
            $reader = new-object System.IO.StreamReader($stream)
            $writer = new-object System.IO.StreamWriter($stream)
            $writer.AutoFlush = $true

            while ($stream.Length -eq 0)
            {
                start-sleep -milliseconds 500
            }
            ReadStream $reader

            WriteStream $Script $writer $stream
        
            $stream.Dispose()
            $sshclient.Disconnect()
            $sshclient.Dispose()

            #Use a Switch statement to build up a list of exceptions to capture as required. If there is no matching exception, it is assumed the execution of the script was a success 
            $results = $reader.ReadToEnd()
            switch -wildcard ($results.ToLower()) 
            { 
                "*invalid input detected*" {Write-Output "Failed to execute script correctly against host '$HostName' for the account '$UserName'. Error = " $results} 
                #Add other wildcard matches here as required
                default {Write-Output "Success"}
            }
        }
        Else 
        {   
            Write-Output "Failed to connect to the host '$HostName' to reset the password for the account '$UserName'. Please check the host is online, or if a Firewall is blocking access."
        }
    } catch {
        Write-Output "Failed to reset password for account '$UserName' on Host '$HostName'. Error = " $error[0].Exception
   }
}


#Make a call to the Set-CiscoHostPassword function
cls
Set-CiscoHostPassword -HostName '10.0.0.253' -Port '22' -UserName '[UserName]' -OldPassword '[OldPassword]' -NewPassword '[NewPassword]'
Thanks
Mark

New Post: Timeout establishing SSH sessions

$
0
0
Stack Trace below:-

System.Management.Automation.MethodInvocationException: Exception calling "RunCommand" with "1" argument(s): "Session operation has timed out" ---> Renci.SshNet.Common.SshOperationTimeoutException: Sessio
n operation has timed out
at Renci.SshNet.Session.WaitHandle(WaitHandle waitHandle)
at Renci.SshNet.SshCommand.BeginExecute(AsyncCallback callback, Object state)
at Renci.SshNet.SshClient.RunCommand(String commandText)
at CallSite.Target(Closure , CallSite , Object , Object )
--- End of inner exception stack trace ---
at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
at System.Management.Automation.Interpreter.ActionCallInstruction2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.Interpreter.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.LightLambda.RunVoid1[T0](T0 arg0)
at System.Management.Automation.PSScriptCmdlet.RunClause(Action
1 clause, Object dollarUnderbar, Object inputToProcess)
at System.Management.Automation.CommandProcessorBase.Complete()

Commented Unassigned: How to read linux cmd output all lines [1963]

$
0
0
Hi,

I am using SSH.Net library to connect linux server and executing some cmds. I am trying to read the out put of the command like below.. but it is returning only first row of the result. If I ran the same cmd in linux directly i will get multiple rows result. Please help to fix my code.

```
var cmd = ssh.CreateCommand("mycmd"); //It is a linux shell script it ran and gives output
var asynch = cmd.BeginExecute(delegate(IAsyncResult ar)
{
Response.Write("Finished.");
}, null);
var reader = new StreamReader(cmd.OutputStream);
while (!asynch.IsCompleted)
{
var result = reader.ReadLine();
Response.Write(result);
if (string.IsNullOrEmpty(result))
continue;

}
cmd.EndExecute(asynch);
```
Comments: ** Comment from web user: da_rinkes **

Maybe the Output is hiding in Stderr/ExtendedOutputStream?
You can check it with redirecting Stderr to /dev/null:

$ your_command 2> /dev/null


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

Looks good with the current sources. 60000 runs and no exceptions. Good job!

New Post: Can I use

$
0
0
Can i use this library in commercial program? I don't see any exclusion in the BSD license?

New Comment on "Documentation"

$
0
0
Where is the sample code for SFTP (simple upload)?

Created Unassigned: WARNING: no suitable primes in /etc/primes [1973]

$
0
0
On some very strict servers a connect attempt with SSH.NET can lead to a warning of the sshd:
"WARNING: no suitable primes in /etc/primes"
This is because SSH.NET requests 1024 bits for group-exchange during kex and in /etc/moduli
(yeah, the file is name different than in the warning, but this is a OpenSSH-Issue) are no 1024 bits entries.
Connection is still established succesfully, but this warning may irritate people.

```
this.SendMessage(new KeyExchangeDhGroupExchangeRequest(1024,1024,1024));
```
So SSH.NET requests min 1024, max 1024 and prefers 1024.

I changed in KeyExchangeDiffieHellmanGroupExchangeSha256.cs:
```
this.SendMessage(new KeyExchangeDhGroupExchangeRequest(1024,1024,8192));
```
and
```
MaximumGroupSize = 8192
```

So now 8192 bits are the maximum.
With this changes client/server choose 2048 bits, the warning disappears and the connection is still working fine.
I'm not sure if the strict 1024 bits are intended.

Would be nice to have this in the upstream code, since OpenSSH client does the same.
http://www.openbsd.org/cgi-bin/cvsweb/src/usr.bin/ssh/dh.h?rev=1.11;content-type=text%2Fplain
http://tools.ietf.org/html/rfc4419

```
#define DH_GRP_MIN 1024
#define DH_GRP_MAX 8192
```

Commented Unassigned: Message type 120 is not valid [1908]

$
0
0
Hello,

I got following error in the session connect.

"Message type 120 is not valid"

Renci.SshNet.dll!Renci.SshNet.Session.LoadMessage(byte[] data) Line 1539
Renci.SshNet.dll!Renci.SshNet.Session.ReceiveMessage() Line 884 + 0xb bytes
Renci.SshNet.dll!Renci.SshNet.Session.MessageListener() Line 1585 + 0x8 bytes
Renci.SshNet.dll!Renci.SshNet.Session.Connect.AnonymousMethod__4() Line 529 + 0x8 bytes
Renci.SshNet.dll!Renci.SshNet.Session.ExecuteThread.AnonymousMethod__3d(object o) Line 25 + 0xf bytes

Server is at sftp.wrightimg.com. Here is the server info obtained from WinSCP

Session protocol = SSH-2
SSH implementation = WeOnlyDo-wodFTPD 3.1.3.348
Encryption algorithm = aes
Compression = No
File transfer protocol = SFTP-4

I appreciate your help.

Thanks,
-Tony
Comments: ** Comment from web user: gsuttie **

Did you guys find any answers to this - I am now getting this error

Commented Unassigned: Message type 120 is not valid [1908]

$
0
0
Hello,

I got following error in the session connect.

"Message type 120 is not valid"

Renci.SshNet.dll!Renci.SshNet.Session.LoadMessage(byte[] data) Line 1539
Renci.SshNet.dll!Renci.SshNet.Session.ReceiveMessage() Line 884 + 0xb bytes
Renci.SshNet.dll!Renci.SshNet.Session.MessageListener() Line 1585 + 0x8 bytes
Renci.SshNet.dll!Renci.SshNet.Session.Connect.AnonymousMethod__4() Line 529 + 0x8 bytes
Renci.SshNet.dll!Renci.SshNet.Session.ExecuteThread.AnonymousMethod__3d(object o) Line 25 + 0xf bytes

Server is at sftp.wrightimg.com. Here is the server info obtained from WinSCP

Session protocol = SSH-2
SSH implementation = WeOnlyDo-wodFTPD 3.1.3.348
Encryption algorithm = aes
Compression = No
File transfer protocol = SFTP-4

I appreciate your help.

Thanks,
-Tony
Comments: ** Comment from web user: tonychan **

Since I could not afford to wait for the fix, I have switched to use WinSCP's .NET library.

http://winscp.net/eng/docs/library

New Post: CreateShellStream - # columns question

$
0
0
I know this is going to be a very odd question, but here it goes.

I have successfully created my SSH connection.
Using CreateShellStream("xterm", 80 , 24, 9600,9600,1024)

When I do an ls (Linux directory listing) :
I get 4 columns as that is all that fits into 80 columns.

Using CreateShellStream("xterm", 132, 24, 9600,9600,1024)

When i do an ls:
 I get 6 columns as that is all that can fit into 132 columns.
So my question,

Is there a way to tell the current stream to please use 132 columns for my next command not 80 that I originally told it?


I am guessing the SSH really cares about the # columns in the CreateShellStream as that seems to be the only way I am able to get more columns or less columns.


Thanks

New Post: Netconf - Is the feature built

New Post: Get the string result from Execute() during the execution

$
0
0
<response to non-technical bullshit>
You cut and snip my words out of context to make your argument? And patronize under the false pretence of giving "advice".. Really? And you talk about being polite and considerate? You are in no position to lecture anyone on forum etiquette.. ever. And you are certainly not in a position to be patronizing.. One word comes to mind: pathetic.

And your two cents are worth zero to me, or anyone reading this forum to get answers or understand ssh.net for that matter.

And dont worry... I would find better technical advice in google translating a drunk russian hobo ramblings than you guys (or the one person hiding behind two pseudonyms). So thanks, but no thanks..

Mixing up technical terms is just the tip of the iceberg in what is your total lack of insight.. And that explains why you get so defensive right off the bat, protecting your ego because of your insecurities.

I don't make fun of non-native speakers, I am one myself.. But I do make fun of people trying to be smarter than they are.
We are on the same team.. just in different leagues;) But you just dont get it..

And yes.. my late response really is a measure of how little I regard you and your "input".
</response to non-technical bullshit>

To anyone interested in the OP question. You cannot/should not read the response stream before the command has completed. However it wouldn't be too difficult to implement the option to read the response concurrently in a thread safe manner if you need it. I did not as it was a nice to have feature, and not need to have.

New Post: Get the string result from Execute() during the execution

$
0
0
Aye, let's get back to topic. Sorry we got your writings wrong. But you must accept you are quite offensive too, not to say quite lordly ;)

I'm not sure I get your statement right. Why shouldn't/can't you read from the response stream during execution?
I actually do it for "downloading" files with cat and/or custom shell-extensions.

New Post: Get the string result from Execute() during the execution

$
0
0
"And dont worry... I would find better technical advice in google translating a drunk russian hobo ramblings than you guys (or the one person hiding behind two pseudonyms).

So thanks, but no thanks.. "

I'm sure nobody here will have any difficulty complying with your wish.

New Post: No docs? No test dir? What am I missing?

$
0
0
Downloaded the latest version, unzip, compiles, everything good so far.

Look for examples on how to simply connect to a host. Hmm. Web site suggests looking at all of the test cases. Ok, look for test cases. Nope. No test cases, no test directory no test files.

Spent better half of day looking for something to show an example of a simple connection.
Found a scrap where you can specify a port forward. Ok, close, but perhaps not enough?

What I'm trying to do:

Connect to a cellular modem that's attached to my PC and get configuration info. I can do this through Putty without a hitch. Want to add code to my app to do this automatically.

Code:

using (var client = new SshClient(IPAddress, "admin", Password))
{
client.HostKeyReceived += client_HostKeyReceived;
client.Connect();
var sshCMD = client.CreateCommand("get"); // modem specific command to send config data
sshCMD.Execute(); // Exception here - see note below
var myres = sshCMD.Result;
   .
   .
   .
client.Disconnect();
}

Error received:"Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection."

Notes:
  1. Thinking perhaps this is some kind of buffer overflow, I specified a command that would normally only return a small number of characters (<30) and it errors the same.
  2. Looked for the "test" cases across the web, and there's a few bits here and there, but none of the code shows the basic flow of connect->command->result
This really shouldn't be that hard.
Viewing all 2955 articles
Browse latest View live


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