我需要能够在我的Linux (Fedora 10)上创建用户帐户,并通过bash脚本自动分配密码(如果需要,也可以采用其他方式)。

通过Bash创建用户很容易,例如:

[whoever@server ]#  /usr/sbin/useradd newuser

是否可以在Bash中分配密码,功能类似于此,但自动:

[whoever@server ]# passwd newuser
Changing password for user testpass.
New UNIX password:
Retype new UNIX password: 
passwd: all authentication tokens updated successfully.
[whoever@server ]#

当前回答

您可以运行passwd命令并向其发送管道输入。所以,你可以这样做:

echo thePassword | passwd theUsername --stdin

其他回答

您可以在bash脚本中使用expect。

从http://www.seanodonnell.com/code/?id=21

#!/usr/bin/expect 
######################################### 
#$ file: htpasswd.sh 
#$ desc: Automated htpasswd shell script 
######################################### 
#$ 
#$ usage example: 
#$ 
#$ ./htpasswd.sh passwdpath username userpass 
#$ 
###################################### 

set htpasswdpath [lindex $argv 0] 
set username [lindex $argv 1] 
set userpass [lindex $argv 2] 

# spawn the htpasswd command process 
spawn htpasswd $htpasswdpath $username 

# Automate the 'New password' Procedure 
expect "New password:" 
send "$userpass\r" 

expect "Re-type new password:" 
send "$userpass\r"

我也问过自己同样的问题,但不想依赖Python脚本。

这是在一个bash行中添加一个具有已定义密码的用户的行:

useradd -p $(openssl passwd -crypt $PASS) $USER

下面是我在Ubuntu 14.04上测试的。它是一个不需要任何用户输入的一行程序。

sudo useradd -p $(openssl passwd -1 $PASS) $USERNAME

摘自@Tralemonkey

在Debian和Red Hat上都可以工作的解决方案。依赖于perl,使用sha-512散列:

cat userpassadd
    #!/usr/bin/env bash

    salt=$(cat /dev/urandom | tr -dc A-Za-z0-9/_- | head -c16)
    useradd -p $(perl -e "print crypt('$2', '\$6\$' . '$salt' . '\$')") $1

用法:

userpassadd jim jimslongpassword

它可以有效地作为一行程序使用,但你必须自己在正确的地方指定密码、盐和用户名:

useradd -p $(perl -e "print crypt('pass', '\$6\$$salt\$')") username

对于RedHat / CentOS,下面是创建用户、添加密码并使用户成为sudoer的代码:

#!/bin/sh
echo -n "Enter username: "
read uname

echo -n "Enter password: "
read -s passwd

adduser "$uname"
echo $uname:$passwd | sudo chpasswd

gpasswd wheel -a $uname