Shak
Shak

Reputation: 133

How to terminate script from within expect script

I have an expect script that ssh's into a server to validate that the password that it is uses is correct. However, in the case it detects an incorrect password, although it does stop the expect command, it continues on with the rest of the script.

The code is below - my question is what command (if there is one) can we put in the fail case (incorrect password) and have it terminate the script so it doesn't continue with the rest of the functionality as if the password was correct.

expect <<-EOS
        #!/usr/bin/expect
        log_user 0
        set timeout $EXP_TIMEOUT
        puts "\nValidating Password...\n"
        spawn ssh -q -o ConnectTimeout=$SSH_TIMEOUT -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${hostname}
        expect "*assword*"
        send -- "$secret\r"
        expect {
                "*assword*" {
                        send \x03
                        puts "\nIncorrect Password\n"
                }
                "$prompt" {
                        send -- "exit\r"
                        puts "\nPassword Validated\n"
                }
        }
        expect eof
EOS

Any help would be appreciated!

edit: I am using bash. The code pasted above is a function in an overall bash script.

Upvotes: 1

Views: 3697

Answers (2)

Shak
Shak

Reputation: 133

I added the following to my code and it seems to work. If anyone has any critiques, please feel free to let me know what could be improved.

expect command:

expect <<-EOS
        #!/usr/bin/expect
        log_user 0
        set timeout $EXP_TIMEOUT
        puts "\nValidating Password...\n"
        spawn ssh -q -o ConnectTimeout=$SSH_TIMEOUT -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${hostname}
        expect "*assword*"
        send -- "$secret\r"
        expect {
                "*assword*" {
                        send \x03
                        puts "\nIncorrect Password\n"
                        exit 1
                }
                "$prompt" {
                        send -- "exit\r"
                        puts "\nPassword Validated\n"
                }
        }
        expect eof
        exit 0
EOS

Parent Bash Script:

if [ $? == 1 ] 
then 
echo "Password validation failed. Exiting..."
exit
fi

Upvotes: 2

CoinBank
CoinBank

Reputation: 47

What coding language are you using? For many languages there is a simple code to exit the application such as this.Exit() in C# or exit() in python.

Upvotes: 1

Related Questions