Search code examples
bashexpect

Expect script continues to run even the expect does not match anything


#!/usr/bin/expect 
spawn ssh admin@10.10.10.10 -o StrictHostKeyChecking=no
expect "5555:"
send "$password\n"
expect "% "
send "exit\n"

No matter what value wrote on expect "5555:" this command still working and I have ssh connection.


Solution

  • You should set a timeout and an action upon the timeout:

    #!/usr/bin/expect
    set timeout 5 
    spawn ssh admin@10.10.10.10 -o StrictHostKeyChecking=no
    expect {
       "5555:"  { }
       timeout { exit 2 }
    }
    send "$password\n"
    expect "% "
    send "exit\n"
    

    Some extra info: the default timeout is 10 seconds. While expecting something, if the pattern has not been seen after $timeout seconds, the expect command without a "timeout" pattern simply returns and the script continues.