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 2.2 by 142 people

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

SshExec Example

Friday, 20 February 2009 04:53 by Tamir

The following sample shows how to use the SshExec class of SharpSSH:

SshConnectionInfo input = Util.GetInput();
SshExec exec = new SshExec(input.Host, input.User);
if(input.Pass != null) exec.Password = input.Pass;
if(input.IdentityFile != null) exec.AddIdentityFile( input.IdentityFile );

Console.Write("Connecting...");
exec.Connect();
Console.WriteLine("OK");
while(true)
{
    Console.Write("Enter a command to execute ['Enter' to cancel]: ");
    string command = Console.ReadLine();
    if(command=="")break;
    string output = exec.RunCommand(command);                
    Console.WriteLine(output);
}
Console.Write("Disconnecting...");
exec.Close();
Console.WriteLine("OK");

Currently rated 3.2 by 68 people

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

SSH Expect Example

Thursday, 19 February 2009 05:02 by Tamir

The following sample shows how to use expect concept with the SshShell class of the SharpSSH library. This sample is also available in the SharpSSH examples found inside the source package zip file.

SshExpectTest.cs

SshConnectionInfo input = Util.GetInput();
SshShell ssh = new SshShell(input.Host, input.User);
if(input.Pass != null) ssh.Password = input.Pass;
if(input.IdentityFile != null) ssh.AddIdentityFile( input.IdentityFile );

Console.Write("Connecting...");
ssh.Connect();
Console.WriteLine("OK");


Console.Write("Enter a pattern to expect in response [e.g. '#', '$', C:\\\\.*>, etc...]: ");
string pattern = Console.ReadLine();

ssh.ExpectPattern = pattern;
ssh.RemoveTerminalEmulationCharacters = true;

Console.WriteLine();
Console.WriteLine( ssh.Expect( pattern ) );

while(ssh.ShellOpened)
{    
    Console.WriteLine();
    Console.Write("Enter some data to write ['Enter' to cancel]: ");
    string data = Console.ReadLine();
    if(data=="")break;
    ssh.WriteLine(data);

    string output = ssh.Expect( pattern );
    Console.WriteLine( output );
}

Console.Write("Disconnecting...");
ssh.Close();
Console.WriteLine("OK");

Currently rated 3.1 by 83 people

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

KeyGen.cs

Wednesday, 18 February 2009 21:04 by Tamir

The following sample demonstrates the RSA/DSA keypair generation feature of SharpSSH. It asks the user for a passphrase and a location of the output_keyfile.

If everything works fine, you it will generate the DSA or RSA keypair files named 'output_keyfile' and 'output_keyfile.pub'. The private and public key files are in the OpenSSH file format.

View the latest versison of this file here.

KeyGen.cs

using System;
using Tamir.SharpSsh.jsch;

/* KeyGen.cs
 * ====================================================================
 * The following example was posted with the original JSch java library,
 * and is translated to C# to show the usage of SharpSSH JSch API
 * ====================================================================
 * */
namespace sharpSshTest.jsch_samples
{
    /// <summary>
    /// This progam will demonstrate the RSA/DSA keypair generation.
    /// You will be asked a passphrase for output_keyfile.
    /// If everything works fine, you will get the DSA or RSA keypair,
    /// output_keyfile and output_keyfile+".pub".
    /// The private key and public key are in the OpenSSH format.
    /// </summary>
    public class KeyGen
    {
        public static void RunExample(params string[] arg)
        {
            if(arg.Length<3)
            {
                Console.Error.WriteLine(
                    "usage: java KeyGen rsa output_keyfile comment\n"+
                    "       java KeyGen dsa  output_keyfile comment");
                return;
            }

            try
            {
                //Get sig type ('rsa' or 'dsa')
                String _type=arg[0];
                int type=0;
                if(_type.Equals("rsa")){type=KeyPair.RSA;}
                else if(_type.Equals("dsa")){type=KeyPair.DSA;}
                else
                {
                    Console.Error.WriteLine(
                        "usage: java KeyGen rsa output_keyfile comment\n"+
                        "       java KeyGen dsa  output_keyfile comment");
                    return;
                }
                //Output file name
                String filename=arg[1];
                //Signature comment
                String comment=arg[2];

                //Create a new JSch instance
                JSch jsch=new JSch();

                //Prompt the user for a passphrase for the private key file
                String passphrase=InputForm.GetUserInput("Enter passphrase (empty for no passphrase)", true);


                //Generate the new key pair
                KeyPair kpair=KeyPair.genKeyPair(jsch, type);
                //Set a passphrase
                kpair.setPassphrase(passphrase);
                //Write the private key to "filename"
                kpair.writePrivateKey(filename);
                //Write the public key to "filename.pub"
                kpair.writePublicKey(filename+".pub", comment);
                //Print the key fingerprint
                Console.WriteLine("Finger print: "+kpair.getFingerPrint());
                //Free resources
                kpair.dispose();
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
            return;
        }
    }
}

Currently rated 1.8 by 93 people

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