1

I have an expect script which performs an SSH to a list of servers with the credentials mentioned in the script. It is not throwing any error when it is unable to SSH to a particular server and continues with the next server in the list. I want the script to let me know when it is unable to SSH with the password given. What changes should be made to the script to get this done?

The first script is a shell script which calls the expect script

#!/usr/bin/ksh
for host_name in `cat list`
do
    /home/user1/ssh_script $host_name
done

#!/usr/local/bin/expect -f
set timeout 1
set host_name [lindex $argv 0]
spawn ssh -q -o StrictHostKeyChecking=no "user1\@$host_name"
expect "*assword:"
send "abcd@123\r";
expect "$\r"
puts "user1 loggedin successfully"
exit
interact
2

You can match for a timeout "pattern" in the expect lines. For example,

#!/usr/bin/expect -f
proc abort { } { send_user "Timeout!" ; exit 2 }
set timeout 1
set host_name [lindex $argv 0]
spawn ssh -q -o StrictHostKeyChecking=no "user1\@$host_name"
expect timeout abort "assword:"
send "abcd@123\r"
expect timeout abort "assword: " { send_user "bad password\n"; exit 3 } "$\r"
puts "user1 loggedin successfully"

This adds a one line procedure abort to the start, and the pattern+action sequence timeout abort to each expect. This will call the procedure if the expect times out. The procedure writes a string to stdout and exits with return code 2 instead of the default 0. You can test for this exit code in your ksh script if you want to.


To detect a bad login password, you can look for a second prompt for the password at the same time as looking for the "$" prompt showing you have logged in ok.

  • I modified the script like above in expect ssh script. It is giving the below error. invalid command name "abort" while executing "abort { } { send_user "Timeout!" ; exit 2 }" – Su_scriptingbee Jan 17 '17 at 10:36
  • Oops. I'm sorry, I left out the keyword proc on the 2nd line when copying the program. I've edited the answer with this fix. – meuh Jan 17 '17 at 12:34
  • "Timeout!" is displayed for all servers(including those whose password is different) in the list with this script. – Su_scriptingbee Jan 17 '17 at 15:36
  • I'm not surprised. I would use a timeout of at least 5 seconds for ssh. Perhaps even more will be needed as ssh startup can be quite slow. – meuh Jan 17 '17 at 15:40
  • Increased the time out value to 15 sec and the message "Timeout!" appears to all the servers – Su_scriptingbee Jan 18 '17 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.