0

我正在尝试使用期望将 $PASSWORD 变量内容传递给 passwd。这似乎可以添加用户,但是一旦您尝试使用其中一个用户通过 ssh 登录,它就不起作用了。如果我手动设置密码,那就没问题了。

以前有人遇到过这个问题吗?

USERS=(user1 user2 user3)



generatePassword ()
{
        pwgen 16 -N 1
}

# Check if user is root
if [ $(whoami) != 'root' ]; then
        echo "Must be root to run $0"
        exit 1;
fi

# Check if pwgen is installed:
if [[ $(dpkg -s pwgen > /dev/null 2>&1; echo ${PIPESTATUS} ) != '0' ]]; then
        echo -e "pwgen is not installed, this script will not work without it\n\n'apt-get install pwgen'\n"
        exit 1;
    else
        echo -e "Starting Script...\n\n"
fi

# Iterate through users and add them with a password
for i in ${USERS[@]}; do
        PASSWORD=$(generatePassword)
        echo "$i $PASSWORD" >> passwords

        useradd -m "${i}"

        echo -e "Adding $i with a password of '$PASSWORD'\n"

        expect -c "
            spawn passwd ${i}

            expect \"Enter new UNIX password:\"
            send -- \"$PASSWORD\r\"
            send -- \"\r\"
            expect \"Retype new UNIX password:\"
            send -- \"$PASSWORD\r\"
            send -- \"\r\"
             "
            echo -e "\nADDED $i with a password of '$PASSWORD'\n"
done
4

2 回答 2

0

第一:最直接的问题是您在键入时并没有转义反斜杠文字\r,因此它们只是r在侧面更改为 s expect;似乎可以解决问题的最小可能更改是将这些更改为\\r.


但是——不要那样做:expect与其他语言一样,字符串应该作为文字传递,而不是替换为代码。

expect -f <(printf '%s\n' '
set username [lindex $argv 0];
set password [lindex $argv 1];
spawn passwd $username

expect "Enter new UNIX password:"
send -- "$password\r"
send -- "\r"
expect "Retype new UNIX password:"
send -- "$password\r"
send -- "\r"
') -- "$i" "$PASSWORD"

您还可以将有问题的文字文本保存到文件中,然后运行expect -f passwd.expect -- "$i" "$PASSWORD",这也可以正常工作(并避免依赖<()语法,这是 bash 采用的 ksh 扩展)。

于 2016-07-26T16:10:27.970 回答
0

你根本不需要期望:使用chpasswd而不是passwd

#!/bin/bash
users=(user1 user2 user3)

# Check if user is root
if [[ "$(id -un)" != 'root' ]]; then
    echo "Must be root to run $0"
    exit 1
fi

# Check if pwgen is installed:
if ! dpkg -s pwgen > /dev/null 2>&1; then
    printf "pwgen is not installed, this script will not work without it\n\n'apt-get install pwgen'\n"
    exit 1
else
    printf "Starting Script...\n\n"
fi

# Iterate through users and create a password
passwords=()
for user in "${users[@]}"; do
    useradd -m "$user"
    password="$user:$(pwgen 16 -N 1)"
    passwords+=("$password")
    echo "Adding user '$user' with '$password'"
done 

printf "%s\n" "${passwords[@]}" | chpasswd

我添加了几个必需的引号。
我已经简化了 dpkg 检查。

或者,也许更简单,newusers以原子方式执行“useradd”和“passwd”功能。

for user in "${users[@]}"; do
    password="$user:$(pwgen 16 -N 1)"
    password=${password//:/-}         # replace all colon with hyphen
    printf "%s:%s::::/home/%s:/bin/bash\n" "$user" "${password//:/-}" "$user"
done | newusers

我不认为 newusers 从 /etc/skel 填充主目录。

于 2016-07-26T23:28:12.697 回答