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

New Post: Dealing with "prompts"

$
0
0
@All,

Well, Codeplex hosed that reply up pretty well.

Let me know if the A & B pointers are confusing...

Also, buried in the above is a subtle 'cry for help' if anyone out there has gotten big data back from a host AND gotten this to work:
Dim asynch As System.IAsyncResult = cmd.BeginExecute()
If asynch.IsCompleted() then
[...]
I'd love to get out of the timeout business, but today, I need it... :(

Always happy to share!

pat
:)
_
NOTE: There also may be a subtlety revolving around a command prompt being RETURNED, and the command prompt being ECHOED..._

New Post: Server String is null or empty

$
0
0
@JamesTow,

I use both MySQL and SQL Server, but never the migration tool SSIS... But I have written lots of code against these databases that connect directly on 3306, and it isn't SSH. It's just plain TCP (and some UDP uses) with their clients, or a more universal DBI. In Visual Studio, I use SMO (Server Management Objects), and I can roll my own anything with that...

Check out here: http://technet.microsoft.com/en-us/library/bb522534%28v=sql.110%29.aspx to get started with connecting, and note that SSIS seems to come with a few tools (on the command line, and probably libraries) that connect for you. Odds are, that is what you are trying to do in the code above with the library you mentioned.

SSH is applied on a server/host as a dedicated daemon (or 'service' in windows parlance) that sits on (default) port 22. It is not associated with any programs, but rather creates a 'tunnel' between the calling client and the connected server that makes the data transferred harder to decode, but also more importantly facilitates the use of security options like certificates.

In addition, SSH is what we call in UNIX/Linux circles a 'terminal program', or 'shell'. This means that once that connection I talked about is made, the software on both sides sees that connection as just a command line waiting for you or a program of your choosing to type something in and hit Enter. SSH is also a protocol, meaning it is just a language that 2 computers can talk. What you and the target host say to each other is translated into SSH-speak as it travels between you, but to each other it looks like a DOS/Bash shell, in that it is in cleartext.

Bottom Line: If you are not using SSH, then you don't need SSH, and SSH will not work for you.

Some info to help you understand more:

SQL Server Integration Services on Wikipedia
SSIS Top Level Page on TechNet
[Connecting to SSIS on TechNet](Connect to a Remote Integration Services Server (SSIS Service))

The previous links will get you connected to SSIS, the following links will get you up to speed on not just when to use SSH (and eventually you will), but also how.

Secure Shell on Wikipedia
SSH2 on Wikipedia
Tunneling with SSH on Wikipedia
SSH2 RFCs and nitty-gritty details on SnailBook
Secure Shell Protocol on Cisco
...and finally...
The excellent An Overview of the Secure Shell (SSH) PDF by VanDyke Software

All the best!

pat
:)

New Post: Dealing with "prompts"

$
0
0
BogusException wrote:
@Festive,

[Yes, I write in both, and Java, and Perl, and... so no nasty comments; Just using the right tool for the job]
Ah Java :) she was my first. I completely agree, use the right tool for the job!

Thanks for taking the time to reply, you've given me a lot that I can use there. As you suspected the prompt text is not the last line I receive, its the last but 1 and the actual prompt is an empty string. But thats fine as I just scan through the last few entries to find it. I guess my issue is with my solution its looking for the response of the command without the capability of issuing further parameters. But I shall solider on with your suggestions!

New Post: Dealing with "prompts"

$
0
0
@Festive,

I'm far from perfect with this library. If you find a sure-fire way to make asynch.IsComplete() work, I'm your disciple!

Frankly, my suspicion is that SSH, or any client in a 'shell' environment for I/O, really can't have any way of knowing whether the stream response is done.

A good example included the *nix 'tail' command, and any Windows equivalents (I guess ping with lots of iterations would be close). I say this because even after a particular shell returns the prompt, it may not be done yielding content. I hope that makes sense to someone out there... :)

As for Java, you have to respect her. She's STILL the only truly OO language there is. Unfortunately, all high level languages today have to have 'interpreters', which convert source to intermediate language (MSIL is no exception), so virtually no programmer today programs against the CPU/HW they are using. That has brought about a whole other set of problems, where quality of developers as suffered from making programming more like block diagrams and dummy lights. MS has it's own version of this in VS, called LightSwitch...

Anyway, I hope you can make progress, and post back a better way for us to use this library! :)

pat
:)

New Post: Dealing with "prompts"

$
0
0
Well I thought id made progress, but apparently using the ShellStream fudges up creating a command and trying to read the result. If I create a stream and then use: result = resultStream.ReadToEnd(); it just hangs and doesnt run Asynch like its supposed to. Stupid machine kicks box

Here is how i implemented sending a command and looking for a return:
    public static void SendShellCommand(string command, List<string> passCriteria, TimeSpan timeout)
    {
        stream.Flush();
        var reader = new StreamReader(stream);
        var writer = new StreamWriter(stream);
        int numOfPassCriteriaMet = 0;
        int numOfPassCriteriaExpected = passCriteria.Count;
        bool passCriteriaMet = false;
        string line = "";
        String[] output;
        Stopwatch myWatch = new Stopwatch();

        try
        {
            writer.AutoFlush = true;
            stream.Flush();
            myWatch.Start();
            writer.WriteLine(command);
            line = "";

            while (myWatch.Elapsed < timeout & passCriteriaMet == false)
            {

                line = line + reader.ReadToEnd();
                output = line.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                resultArray = output;

                foreach (string value in passCriteria)
                {
                    foreach (string outputValue in output)
                    {
                        if (outputValue.Contains(value, StringComparison.CurrentCultureIgnoreCase))
                        {
                            numOfPassCriteriaMet++;
                        }
                        if (numOfPassCriteriaMet == numOfPassCriteriaExpected)
                        {
                            passCriteriaMet = true;
                            break;
                        }
                    }
                    if (passCriteriaMet)
                    {
                        break;
                    }
                }
                Thread.Sleep(100);
            }

            myWatch.Stop();
            myWatch.Reset();

            if (passCriteriaMet)
            {
                WebDriver.myLogger.LogPass("Executed VMS command: " + command);
            }
            else
            {
                WebDriver.myLogger.LogFail("One or more steps failed executing the VMS command: " + command);

                    foreach (string result in resultArray)
                    {
                        string comment = Regex.Replace(result, @"[^\u0000-\u007F]", string.Empty);
                        WebDriver.myLogger.LogComment(comment.Trim());
                    }
            }
        }
        catch(Exception ex)
        {
            myWatch.Stop();
            myWatch.Reset();
            WebDriver.myLogger.LogFail("Error executing VMS command: " + command + " | " + ex.Message);
        }
        WebDriver.TestLog().LogStep(WebDriver.TestLog().GetTestResult(), "Execute command");

    }

New Post: Dealing with "prompts"

$
0
0
Ive managed to get a version of this working quite robustly, when i've tested it enough i'll post it here! :)

Jelly

New Post: Dealing with "prompts"

Patch Uploaded: #16641

$
0
0

xin_scott has uploaded a patch.

Description:
When the case in the Program.cs, Encrypt method will throw a exception.
I have fix the issue successfully:)


New Post: How to retrieve stdout & stderr both from Invoke-SshCommand

$
0
0
Hello,
I'm running the invoke-sshcommand cmdlet and I can't seem to get both pipes. Invoke-sshcommand seems to return one or the other. If I expect output from stdout only, I get it. If I expect output through stderr, I get it. I have a program that should get output from both pipes but all I get is sdterr. The cmdlet seems to clobber stdout with stderr. How do I get both pipes through invoke-sshcommand?

DLL module is 2013.4.7
psd1 file is 1.0.0.4

Thanks.

New Post: How to retrieve stdout & stderr both from Invoke-SshCommand

$
0
0
This page is for the library only. Many PowerShell modules use it (including my own). You should check first with the author of the module how he coded the use of the library. Whose PowerShell module are you using and what commands are you trying to run and how? most use sshexec, so a command is ran and the shell is closed so state is lost.

New Post: How to retrieve stdout & stderr both from Invoke-SshCommand

$
0
0
Darkoperator wrote:
This page is for the library only. Many PowerShell modules use it (including my own). You should check first with the author of the module how he coded the use of the library. Whose PowerShell module are you using and what commands are you trying to run and how? most use sshexec, so a command is ran and the shell is closed so state is lost.
I'm using Renci.sshClient. I will contact them. Sorry.

New Post: How to use ShellStream class ?

$
0
0
Hi All,

can someone please post code or reference a link for an example on how to use the ShellStream class ?

I can attach to an SSH server, run some commands, display its results, but I need to go further.

Now, what I need to do is to wait for certain prompts in the server's response and supply answers. For instance, I want to telnet to a device from the SSH server and I need to make the logon interactive.

I can see ShellStream has an Expect(string text) method, I just need an example of how to use that.

Thanks in advance.

Commented Unassigned: Server string is null or empty Issue [2223]

$
0
0
can you help me understand why Session.cs is throwing an InvalidOperationException of "Server string is null or empty." when it is attempting to read the response(s) coming back from the connection attempt?
It seems this exception will always be thrown if the first line in the response is NULL or empty.
Which is happening to me.

If I remove this thrown exception and allow the full timeout on the ConnectionInfo to expire, my connection is eventually made and the server version is returned in the response.
Comments: ** Comment from web user: sergioesp **

This is happening to me as well. In my case, the server returns a welcome message, blank line, and then the version.

Created Unassigned: Running a shell script with result - nohup: redirecting stderr to stdout [2359]

$
0
0
Hi Everyone!

Need all of your help greatly to enlighten me on this issue. I have developed a automation tool to perform some daily task. But my application does not run the next command after it returns

__nohup: redirecting stderr to stdout__

usually on mobaxterm I would be required to press "Enter" to move on to the next command.

Is there anyway on SSH.Net library I could execute/simulate an "Enter" button press on it when the expected result nohup: redirecting stderr to stdout comes out?

Regards,

oddler

New Post: Need help with sending keypress / any workarounds.

$
0
0
Hi Everyone!

Need all of your help greatly to enlighten me on this issue. I have developed a automation tool to perform some daily task. But my application does not run the next command after it returns so it end up waiting for something to happen. The command below is expected.

nohup: redirecting stderr to stdout

usually on mobaxterm I would be required to press "Enter" to move on to the next command.

Is there anyway on SSH.Net library I could execute/simulate an "Enter" button press on it when the expected result nohup: redirecting stderr to stdout comes out?

Regards,

oddler

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

Hi, I am running into a similar issue and was wondering if you ever to fix this error. Any help is appreciated.

Created Unassigned: SftpClient and SshClient usage (Renci.SshNet V2013.4.7.0 dll) cannot connect to the logical machine [2369]

$
0
0
Hi,

Currently we are using Renci.SshNet V2013.4.7.0 dll for connecting to FTP host. But seems that it is working correctly if we map to a physical host but fails to connect if it is a logical Host.

The Unix Team in our organisation advised on changing the following options:

StrictHostkeyChecking (needs to be set to no)
UserKnownHostsFile (should be set to /dev/null)
NoHostAuthenticationForLocalHost (should be set to yes)

Can anyone guide us as to how to do these from the application code.

Please advise if you need further details.

Thanks

Ali.

New Post: Port Forwarding and Java application launch

$
0
0
Hello all, first of all thank you for this great community, I am learning a lot as I go. I am by no means a programmer by trade, I write code with a means to and end approach, and so any solution I came to is usually far from elegant. I also do not know much about the various ways to debug but I will try to pull together as much information for those willing to help as I can. Also, I apologize for any incorrect use of jargon.

The problem I am having is with, as the title suggests, Port Forwarding and launching a Java application. I am able to successfully create an ssh tunnel to my server with the following code.
                        pubfile = new PrivateKeyFile("C:\\System Apps\\" + _SSHkeyfile, _SSHpassword);
                        sshclient = new SshClient(_HostURI, _SSHPort, _SSHusername, pubfile);
                        sshclient.Connect();
                        forport1 = new ForwardedPortLocal("127.0.0.1", 65088, "127.0.0.1", 8088);
                        forport2 = new ForwardedPortLocal("localhost", 65088, "localhost", 8088);
                        sshclient.AddForwardedPort(forport1);
                        sshclient.AddForwardedPort(forport2);
                        System.Threading.Thread.Sleep(1000 * 1);
                        forport1.Exception +=new EventHandler<ExceptionEventArgs>(forport1_Exception);
                        forport1.Start();
                        forport2.Start();
I know it's working because the server hosts a webpage at 127.0.0.1:65088, and I am able to load firefox and navigate to said page and click through any number of links that reside on the page. However whenever I try to launch a Java application, the application is able to download to my local computer but when the application runs I receive the following error.

System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
at Renci.SshNet.Session.WaitOnHandle(WaitHandle waitHandle)
at Renci.SshNet.Channels.Channel.Close(Boolean wait)
at Renci.SshNet.Channels.ChannelDirectTcpip.Close()
at Renci.SshNet.ForwardedPortLocal.<>c__DisplayClass3.<InternalStart>b__2()

from the ForwardedPortLocal ExceptionEventArgs and this error

System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.Send(Byte[] buffer, Int32 offset, Int32 size, SocketFlags socketFlags)
at Renci.SshNet.Channels.ChannelDirectTcpip.InternalSocketSend(Byte[] data)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Renci.SshNet.Session.MessageListener()

from the SshClient ExceptionEventArgs.

What's interesting is that I was able to load the java application 1 time, and every time since then I get a "Connection Refused" as reported by the Java application.

I am able to use Putty to connect and load the Java application with no problems.

Any and all help is much appreciated, thanks!

New Post: Port Forwarding and Java application launch

$
0
0
I've gotten this to work with the older SharpSSH library. I also used TCPView from Microsoft to watch what happens when the connection are created. It seems that when the java application is launched it begins by opening up many connections which are all routed through the 65088 port originating from various remote ports. These all seem to Open, Establish and Close_Wait very quickly. Sometimes a Close_Wait port will open up again and begin transmitting data but most times the ports remain closed, while only two will remain Established and one will be transmitting data.

I'm not sure if any of this makes sense, I could take a screenshot and show you whats happening in TCPView if anyone would like to investigate this. This could also be a problem with the java application that I open?

If I had to guess, it would appear that ssh.net has a problem handling the many opening and closing requests sent rapid fire over the one forwarded port.

New Post: Using Renci SSH.NET with Expect.NET?

$
0
0
Experts,

I stumbled onto Expect.NET (NuGet here), and before I go crazy looking, have any of you used is with SSH.NET?

I'm new to it, so I don't see how to 'attach' Expect to an SSH.NET session yet.

For those unaware, a test ping program I modified from the examples Expect comes with looks like this:
Imports ExpectNet

Module Module1

    Sub Main()
        Dim s As Session = Expect.Spawn(New ProcessSpawnable("cmd.exe"))
        Try
            s.Expect(">", Sub(x) Console.WriteLine("Prompt --> " + x))
            s.Timeout = 1000
            s.Send("dir c:\" + Environment.NewLine)
            s.Expect("Program Files", Sub(x) Console.WriteLine(x))
            s.Expect(">", Sub() s.Send("ping 8.8.8.8" + Environment.NewLine))
        Catch ex As System.TimeoutException
            Console.WriteLine("Timeout")
        End Try
        s.Timeout = 500
TRY_AGAIN:
        Try
            s.Expect("Lost = 0", Sub() s.Send("ping 8.8.8.8" + Environment.NewLine))
            s.Expect("Lost = 0", Sub(x) Console.WriteLine(x))
        Catch ex As System.TimeoutException
            Console.WriteLine("Timeout({0})", s.Timeout)
            s.Timeout += 500
            GoTo TRY_AGAIN
        Catch ex As Exception
            Console.WriteLine("Exception " & ex.ToString)
        End Try
        Console.WriteLine("Done")
        Console.ReadKey()
    End Sub
End Module
Already it is looking like a fantastic way for me to deal with Cisco products. There should be a way to simply point Expect to the ssh session, and let it 'talk' over ssh once SSH.NET has connected, right?

Any pointers appreciated!

pat
:)

P.S. Why I am I asking? Because I know that Expect will call an SSH executable. I am trying not to create vulnerabilities by calling 3rd party programs. Keeping everything ssh inside the app(s) is the best way-providing I can figure it out with your help! :)
Viewing all 2955 articles
Browse latest View live