'What's a good way to ignore garbage output from ssh session in pexpect?
I want to automate a login to a host which outputs junk at the start of the session (due to errors in the profile script which I am unable to correct). Unfortunately the junk contains the prompt string I'm looking for, several times over. Is there an elegant way to wait for the output to settle?
In other words, wait at most XXX mS for the last occurrence of the prompt string.
For example:
prompt = "$ "
child = pexpect.spawn("ssh [email protected]")
# clever stuff here to skip zero or more prompt strings
child.expect_exact(prompt)
Solution 1:[1]
I found no answer to the specific question I was asking about waiting for the output to settle, however there is a relatively simple solution to the problem of obtaining the real prompt, which doesn't involve any waiting, or scanning through the pexpect read buffer looking for patterns.
Just echo something known into the login session once it's connected, and wait for it to be sent back.
child.sendline("echo my unique string")
child.expect_exact("my unique string")
child.expect_exact("$ ")
I put double-spaces in the echo command (which echo removes in the output) so I don't have to match the keyboard echo text. This seems to output my unique text after any junk produced by .cshrc or profile scripts, so I skip over the extra prompt strings just by waiting for this unique string. I can't be certain this will work in all cases, but seems to work for mine.
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 | Keeely |
