Read telnet output in while

0 votes
asked Jan 11, 2016 by Pavel (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;

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
answered Jan 12, 2016 by Pavel Matyska (13,940 points)


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

// password prompt is not a regular prompt

// detects regular prompt (in your case '>')

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

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);

// I suppose after the job is completed, new prompt is received. If not, ignore the following line.

// 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.