title: How to handle errors from passwd in expect script?
body: <p>I'm trying to create an expect script to update a user's password non-interactively. New to expect and shell scripting. I want to be able to capture and handle errors encountered. For example, if I'm running passwd normally, and my new password isn't acceptable for some reason, I might see a message like "BAD PASSWORD: The password is too similar to the old one".
  The problem is that, in the expect script, after send $new_pswd\r with an invalid password, expect "BAD PASSWORD:*" is failing because the next output from passwd is " ".
  I would like to capture the bad passwords and the message so that I can return those to the calling process.
  The use case here is to allow individual users who may have multiple accounts to update all their accounts with the same password in one go. This script would be called once for each account.</p>
  
  <pre><code>#!/usr/bin/expect -df
  
  # THIS SCRIPT WON'T WORK
  set old_pswd $::env(PSWD1)
  set new_pswd $::env(PSWD2)
  
  spawn passwd
  expect "*ssword:" { send "$old_pswd\r" }
  expect "*ssword:" { send "$new_pswd\r" }
  expect {
          "*ssword:" {
                  puts "Expected\r"
                  send "$new_pswd\r"
                  exit 0
          }
          "BAD PASSWORD:*" {
                  puts "BAD PASSWORD\r"
                  send \x03
                  exit 1
          }
          "*" {
                  puts "Unexpected\r"
                  send \x03
                  puts $expect_out(buffer)
                  exit 1
                  }
          }
  </code></pre>