When using Expect to run commands on a remote Un*x system, we can trigger off of carefully-constructed events, to give us greater insight into the state of the remote machine:
event: process ended
Instead of running some_command, we run some_command; echo 's'ome_command_ended. If we ever see the string "some_command_ended" sent back, then we know for sure that that command ended.
This is PARTICULARLY useful when we're running sudo/ssh/telnet from a remote host (ie. we're doing multi-hop connections). If we ever see the trigger string, then we know that the telnet/ssh command finished, and that we have returned to the previous machine in the connection-chain.
event: shell started
If we just entered the password, and we think the shell will be starting soon, we can send a command like echo 's'hell_started_detected. If we ever see the string "shell_started_detected" sent back, then we know the shell started successfully.
The usual procedure is to wait for the machine's prompt. This technique allows us to detect the shell-start event in a prompt-independent way. (however, it does require us to know what the machine's shell is)
event: before process starts
Goal: make sure we can distinguish between a command's output, and the command-line prompt text.
To do this, instead of some_command, we run echo 's'ome_command_beforestart; some_command; echo 's'ome_command_ended. As soon as we see the text "some_command_beforestart", we know that all text after that will be the output of 'some_command'.
We should use long and randomly-generated trigger-strings to ensure that there is no possibility of accidental conflict with normal data.
Here, we're depending on the shell to convert a string like 's'ome_command_started to "some_command_started". It's possible we can't always rely on the remote shell to do this, if the remote shell is something very different from Bash/Csh. (eg. Cisco IOS)
- sz^Home_command_started — We're relying on the ^H to cancel out the 'z' by the time the output string is generated. This probably works in more shells. However, it requires us to know what the 'stty erase' setting is. In some cases, we might be able to try BOTH versions — sz^?ome_command_started as well.
Other pages that attempt to improve the reliability of Expect sessions include: