Using the Expect concept in SharpSSH

Saturday, 21 February 2009 00:25 by Tamir

I get these kind of questions a lot, so I will try to explain a bit the concept of expect.

The whole point of expect is to simulate a session of a real interactive user. A real user typically log into an SSH server using an SSH client. We establish this functionality by creating the SshShell object and connect it:

SshShell ssh = new SshShell(host, user, pass);
ssh.Connect();

After a user has successfully logged in (and before he start entering commands), he typically gets a Shell prompt (sometimes before the prompt you would also get a welcome message). In any case, at this point in our code we need to read the initial response from the server. Depends on your server initial response you should expect this prompt, typically it will just be the regular shell prompt:

ssh.Expect("the initial server prompt");

If from some reason you skip this part, the response you read from the channel will be out of sync, meaning when you write a command and then call expect you will get the response of the previous prompt.

At this point, the user is ready to start entering commands. After each command you should always call expect with the string you want to match.

ssh.WriteLine("ls -lart");
resp = ssh.Expect("shell prompt");
Console.WriteLine(resp);

(See related post on the CodeProject forums page)

Currently rated 5.0 by 2 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:  
Categories:   SharpSSH
Actions:   E-mail | Permalink | Comments (109) | Comment RSSRSS comment feed

Comments

Comments are closed