my $exp = Expect->spawn("sudo passwd -i opendirectory $user_name") or die "Cannot spawn passwd: $!\n";; my $spawn_ok; $exp->expect($timeout, [ qr'New password:$', sub { $spawn_ok = 1; my $fh = shift; $fh->send("$user_password_new1\n"); exp_continue; } ], [ 'Retype new password:$', sub { my $fh = shift; print $fh "$user_password_new1\n"; exp_continue; } ], [ 'password for root:$', sub { my $fh = shift; print $fh "$admin_password\n"; exp_continue; } ], [ eof => sub { if ($spawn_ok) { $exp->hard_close(); $result = "1"; #die "\n"; } else { $exp->hard_close(); $result = "0"; } } ], [ timeout => sub { die "No login.\n"; } ], '-re', qr'[#>:] $', #' wait for shell prompt, then exit expect );