ssh.net maintain conversation with server

1.4k views Asked by At

I am looking to persist a conversation with a remote server using ssh.net

What i am doing is connecting to a host, sending a command like change directory... to some directory besides root. Store the results value off as a global.

Then i am sending another command via RunCommand() to check the current directory...

What is happening is, i am getting the root directory, not the directory i just changed to in the initial run command.

What it seems is happening is, while the connection to the server has remained open i have somehow reset the terminal session thereby losing the conversation i was having with the server.

Does anyone know how to persist a conversation with a remote server using ssh.net so i can send multiple commands and have the state persist?

E.g. command 1 = cd/somedir command 2 = pwd and the result of command 2 to is /somedir

1

There are 1 answers

1
Selcuk OZEN On BEST ANSWER

E.g. command 1 = cd/somedir command 2 = pwd and the result of command 2 to is /somedir

Your example seems just fine. But I think, you are expecting to change directory and run the second command in that directory.

Server connection is an ssh tunnel to the server, it doesn't start a shell. RunCommand() creates a shell and runs a command, the second RunCommand also creates a new shell and runs the command, so change directory does not persist between commands.

After establishing connection, use a ShellStream to create a shell from which you can send and receive interactive commands from.

A sample from codeplex:

    string command = "your command";

    using (var ssh = new SshClient(connectionInfo))
{
    ssh.Connect();
    string reply = String.Empty;

    try
    {
    using (var shellStream = ssh.CreateShellStream("dumb", 0, 0, 0, 0, BUFFERSIZE))
        {
            // Wait for promt for 10 seconds, if time expires, exception is thrown
            reply = shellStream.Expect(new Regex(@":.*>"), new TimeSpan(0, 0, 10));
            shellStream.WriteLine(command);

            // Wait for Read for 10 seconds, if time expires, exception is thrown
            string result = shellStream.ReadLine(new TimeSpan(0, 0, 10));
        }
    }
    catch
    {
        // Do something
    }
}