'How to capture prompt from terminal using Tcl or how can I match prompt with color code?

I want to capture prompt of a remote device.

 -regexp {[\$\#]\s*$} {
       # capture the prompt  
 }

"[\$#]\s*$" does not work for prompt with color codes.



Solution 1:[1]

Colour codes are sent as escape sequences in the character stream. As such, if you have them there you need to match them. Each escape sequence is the ESC character (Esc, ^[, \u001b) followed by various characters terminated with a ; (well, that's the colour setting ones; there are others, and they're somewhat complicated). While yes, you could match these with a more complicated regular expression, it's enormously easier to set the prompt to something simple that you control.

# ...
expect "ssword: "
send $password\r
# Note, *NO* expect at this point as matching it is hard
send "PS1='> '\r"
expect -regexp {> $}

Coloured prompts are nice enough for people, but they're awkward for scripting. Overriding will make your life much easier. (You might also try setting the terminal to a terminal type that doesn't support colours.)

Solution 2:[2]

I have found success using ANSI escape codes like this:


set NO_COLOR "\033"
set RED_COLOR "\[0;31m"
expect {
    "${RED_COLOR} here is red input text ${NO_COLOR}" { puts "matched!" }
}

set NO_COLOR_REGEX "\033\\\[0m"
set RED_COLOR_REGEX "\033\\\[0;31m"
expect {
    -re "${RED_COLOR_REGEX} here is red input text ${NO_COLOR_REGEX}" { puts "matched!" }
}

set RED_OUTPUT "\033\[0;31m"
set NO_COLOR_OUTPUT "\033\[0m"
puts "${RED_OUTPUT} here is some colored output text ${NO_COLOR_OUTPUT}"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Donal Fellows
Solution 2