This project is read-only.

SshShell needing Thread.Sleep between commands

Oct 9, 2013 at 1:25 AM
Hi,

I'm trying to connect to a unix box and run a script. The SshClient.RunCommand does not work because I think the script needs something in the shell to function correctly (I read about a similar problem on another discussion here).

So I've tried using the sshShell to do this:
            // this does not work (unless I am stepping through when debugging)
            
            var sshShell = new SshShell(_host, _user, _pass);

            sshShell.Connect();

            sshShell.WriteLine(command);

            sshShell.Close();
But for the above code when running it normally the script does not appear to be run. It WILL run if I am debugging and stepping through the above code. So, I put some sleeps in and the below code will run ok (_sleepTime is set to 1000):
            // this works

            var sshShell = new SshShell(_host, _user, _pass);
            sshShell.Connect();

            System.Threading.Thread.Sleep(_sleepTime);

            sshShell.WriteLine(command);

            System.Threading.Thread.Sleep(_sleepTime);

            sshShell.Close();
It looks like it needs some time both after the connect and after the command is written. I suspect using sleep is pretty unreliable though, e.g. if the remote server is working hard am I going to need a longer sleep time? So my question is, is there a better more reliable way to do this?

I have also tried the below, but again had the same issue where it will work if debugging but not consistently if I let it run normally:
            var connectionInfo = new PasswordConnectionInfo(_host, _user, _pass);
            using (var ssh = new SshClient(connectionInfo))
            {
                ssh.Connect();
                string reply = String.Empty;

                using (var shellStream = ssh.CreateShellStream("dumb", 0, 0, 0, 0, 1000))
                {
                    // 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));
                }

            }