Search code examples
linuxshellexpectspawn

simulate enter keypress after a command is executed


I am doing SSH to a host and executing a command and the command asks you to press the enter key. (It asks twice for different things.)

I am using spawn expect here.

When you send the report command, it will ask for you to press ENTER key. Once that is done, again it asks you to press enter. I want to send the enter key automatically.

#!/usr/bin/expect
spawn ssh user@host report
expect "Press ENTER to continue, or CTRL-C to quit."
send " \r"
expect "Press enter for inputing"
send "\r"

ENTER should be done automatically and get the end result of the command.


Solution

  • say you have the "report" script on machine "audrey":

    #!/bin/bash
    echo -n "Press ENTER to continue, or CTRL-C to quit."
    read
    echo -n "Press enter for inputing"
    read
    read s
    echo "You sent: $s"
    

    and the local expect script:

    #!/usr/bin/expect
    spawn ssh audrey ./report
    expect "Press ENTER to continue, or CTRL-C to quit."
    send "\n"
    expect "Press enter for inputing"
    send "\n"
    send "OK\n"                                                                           
    expect "You sent: OK"
    close
    

    ./a.expect output:

    spawn ssh audrey ./report
    Press ENTER to continue, or CTRL-C to quit.
    Press enter for inputing
    OK
    You sent: OK