0 votes
by (120 points)

One of the features what I need for my task is read output from console.
For example, I send command via telnet. This command is executed asynchronously, so I can get conclusion after a while.

command -x test.tr;

Prompt sign '>' appears immediately after run the command.
After 1-2 minutes (may be more or less) I will get message like:
Job completed (or another message "Error...").

So I would like read output in loop until don't get some message. Is it possible to do?

1 Answer

0 votes
by (15.2k points)

Hello,

I suppose you would like to write a script that behaves like you described. It can be done like this:

Telnet telnet = new Telnet(serverName);

// get the scripting object
Scripting scripting = telnet.StartScripting();

// login
scripting.ReadUntil("login:");
scripting.SendCommand(username);

// password prompt is not a regular prompt
scripting.ReadUntil("Password:");           
scripting.SendCommand(password);

// detects regular prompt (in your case '>')
scripting.DetectPrompt();

// run asynchronous command
scripting.SendCommand("command -x test.tr;");
// read prompt that appears immediately
scripting.ReadUntilPrompt();

ScriptEvent keepAlive = ScriptEvent.Delay(30 * 1000); // this event works like keep-alive in this context
ScriptEvent success = "Job completed"; // job completed successfully (Place correct message here)
ScriptEvent error = "Error occured"; // some error occured (Place correct message or unique substring of it here)

while (true)
{
    // wait for one of these script event (they are combined with OR operator)
    ScriptMatch match = scripting.WaitFor(success, error, keepAlive);
    // job completed
    if (match.IsEventMatched(success) || match.IsEventMatched(error))
    {
        // read until the end of line (read until '\n' is received);
        scripting.ReadLine();
        break;
    }
}

// I suppose after the job is completed, new prompt is received. If not, ignore the following line.
scripting.ReadUntilPrompt();

// do other jobs now

This is the code of what I have understood from your explanation, so feel free to modify it or describe the server/command behavior with more details.

...