期待命令行脚本

期待命令行脚本

我正在编写一个脚本,允许 Linux 管理员快速更改其用户的密码。

#!/usr/bin/expect
# Check password for strength 
# ----------------------------------------------
read -p "What's your username?" current_user
read -p "What's the root password?" pass
read -p "How many users?" num
COUNTER=0
         while [  $COUNTER -lt $num ]; do
         let index=COUNTER+1
             read -p "Enter username$index : " user_$index
             let COUNTER=COUNTER+1 
         done
read -p "Enter password : " password
echo 
echo "Tesing password strength..."
echo
result="$(cracklib-check <<<"$password")"
okay="$(awk -F': ' '{ print $2}' <<<"$result")"
if [[ "$okay" == "OK" ]]
then
    echo "PASSWORD ACCEPTED"
    echo "Modifying User Passwords..."
    COUNTER=0
         while [  $COUNTER -lt $num ]; do
             let index=COUNTER+1
             tmp=user_$index
             echo "Changing Password for " ${!tmp}
             echo ${!tmp}
             sudo passwd ${!tmp}
             expect -exact "[sudo] password for $current_user: "
             send "$pass\r"
             expect -exact "New password: "
             send "$password\r"
             let COUNTER=COUNTER+1 
         done

    #echo "$user:$password" | usr/sbin/chpasswd
else
    echo "Your password was rejected - $result"
        echo "Try again."
fi

然而,将自动输入密码的期望部分在我的编辑器中没有突出显示并且不起作用。我不断收到手动输入文本的提示。这是特别令人惊讶的,因为脚本是源自expect,而不是bash。过去两个小时我一直在尝试解决这个问题。谁能帮我一下吗?

答案1

您正在混合 Expect 和 bash 代码。您的脚本主要是 bash 脚本,因此请将顶行替换为#!/bin/bash.然后替换行:

sudo passwd ${!tmp}
expect -exact "[sudo] password for $current_user: "
send "$pass\r"
expect -exact "New password: "
send "$password\r"

通过使用mychangepw期望需要的参数调用函数,即当前用户、sudo 密码、要更改的用户及其密码:

mychangepw $current_user "$pass" ${!tmp} "$password"

将函数添加到脚本的开头,并使用它来传递参数到expect,stdin 上的expect 脚本一直到“!”行:

mychangepw(){
    expect -d - "$@" <<\!
    set current_user [lindex $argv 0]
    set sudopass [lindex $argv 1]
    set user [lindex $argv 2]
    set password [lindex $argv 3]
    spawn sudo passwd $user
    expect -exact "\[sudo\] password for $current_user: "
    send "$sudopass\r"
    expect -exact "New password: "
    send "$password\r"
!
}

小心以“!”开头的行。它必须是该行的第一个也是唯一的字符,没有缩进,也没有额外的空格或注释等。

相关内容