Search code examples
linuxremote-accesstelnet

How can I scroll the terminal output with Expect Script?


I'm trying to come up with a simple expect script that allows me to login to a system and run a single command ... something like this:

The problem I have is that the output from a single show command overflows, the display screen is followed by the --More-- prompt. At the --More-- prompt, you have these options:

  • Press Ctrl+C, q, or Q to interrupt the output and return to the command prompt.

  • Press the spacebar to display an additional screen of output.

  • Press Enter to display one more line of output.

What I want at the end is to record all the output from the show command but my script is timing out at the first --More-- prompt. How can I make the script to send new line characters (i.e. spacebar) everytime it gets the --More-- prompt?

Thanks in advance,

!/usr/bin/expect

spawn telnet 192.168.0.1
expect "Username:"
send "MyUsername\r"
expect "assword:"
send "MyPassword\r"
send "show ip int br\r"
interact timeout 5
send -- "exit \r"


Solution

  • If you're dealing with a Cisco terminal (as it appears you are), you can set the terminal length to zero (by sending "term len 0"), as 0 means "no pausing". That's the best approach to avoid the expect script from having to do "extra work" in dealing with paginated output.

    Otherwise you can do something like this:

     expect {
       -ex "--More--" { send -- " "; exp_continue }
       "*#" { send "exit\r" }
     }
    

    The "-ex" is to avoid expect from thinking "--More--" is a flag since it starts with a hyphen. On match, you send a space to scroll another screen, and continue expecting until you get back to a prompt (such as the exec prompt), and exit.