Linux 如何使用 Bash 脚本自动添加用户帐户和密码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2150882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to automatically add user account AND password with a Bash script?
提问by ModernCarpentry
I need to have the ability to create user accounts on my Linux (Fedora 10) and automatically assign a password via a bash script(or otherwise, if need be).
我需要能够在我的 Linux (Fedora 10) 上创建用户帐户并通过 bash 脚本(或其他方式,如果需要)自动分配密码。
It's easy to create the user via Bash e.g.:
通过 Bash 创建用户很容易,例如:
[whoever@server ]# /usr/sbin/useradd newuser
Is it possible to assign a password in Bash, something functionally similar to this, but automatically:
是否可以在 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 ]#
采纳答案by Tralemonkey
You can run the passwd command and send it piped input. So, do something like:
您可以运行 passwd 命令并向其发送管道输入。因此,请执行以下操作:
echo thePassword | passwd theUsername --stdin
回答by R Samuel Klatchko
You can use the -p option.
您可以使用 -p 选项。
useradd -p encrypted_password newuser
Unfortunately, this does require you to hash the password yourself (where passwd does that for you). Unfortunately, there does not seem to be a standard utility to hash some data so you'll have to write that yourself.
不幸的是,这确实需要您自己对密码进行哈希处理(passwd 为您执行此操作)。不幸的是,似乎没有标准实用程序来散列某些数据,因此您必须自己编写。
Here's a little Python script I whipped up to do the encryption for you. Assuming you called it pcrypt, you would then write your above command line to:
这是我编写的一个小 Python 脚本,用于为您进行加密。假设您将其称为 pcrypt,那么您可以将上述命令行写入:
useradd -p $(pcrypt ${passwd}) newuser
A couple of warnings to be aware of.
需要注意的几个警告。
- While pcrypt is running, the plaintext will be visible to any user via the ps command.
- pcrypt uses the old style crypt function - if you are using something more moderns like an MD5 hash, you'll need to change pcrypt.
- 当 pcrypt 运行时,任何用户都可以通过 ps 命令看到明文。
- pcrypt 使用旧式 crypt 函数 - 如果您使用更现代的东西,如 MD5 哈希,则需要更改 pcrypt。
and here's pcrypt:
这是 pcrypt:
#!/usr/bin/env python
import crypt
import sys
import random
saltchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
def salt():
return random.choice(saltchars) + random.choice(saltchars)
def hash(plain):
return crypt.crypt(arg, salt())
if __name__ == "__main__":
random.seed()
for arg in sys.argv[1:]:
sys.stdout.write("%s\n" % (hash(arg),))
回答by Carlos Tasada
You can use expect in your bash script.
您可以在 bash 脚本中使用 expect 。
From http://www.seanodonnell.com/code/?id=21
来自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"
回答by Damien
I was asking myself the same thing, and didn't want to rely on a Python script.
我也在问自己同样的事情,不想依赖 Python 脚本。
This is the line to add a user with a defined password in one bash line:
这是在一个 bash 行中添加具有定义密码的用户的行:
useradd -p $(openssl passwd -1 $PASS) $USER
回答by Carel Lubbe
Here is a script that will do it for you .....
这是一个可以为您完成的脚本......
You can add a list of users (or just one user) if you want, all in one go and each will have a different password. As a bonus you are presented at the end of the script with a list of each users password. .... If you want you can add some user maintenance options
如果需要,您可以添加一个用户列表(或仅一个用户),一次性添加,每个用户都有不同的密码。作为奖励,您会在脚本末尾看到每个用户密码的列表。.... 如果你愿意,你可以添加一些用户维护选项
like:
喜欢:
chage -m 18 $user
chage -M 28 $user
to the script that will set the password age and so on.
到将设置密码年龄等的脚本。
=======
========
#!/bin/bash
# Checks if you have the right privileges
if [ "$USER" = "root" ]
then
# CHANGE THIS PARAMETERS FOR A PARTICULAR USE
PERS_HOME="/home/"
PERS_SH="/bin/bash"
# Checks if there is an argument
[ $# -eq 0 ] && { echo >&2 ERROR: You may enter as an argument a text file containing users, one per line. ; exit 1; }
# checks if there a regular file
[ -f "" ] || { echo >&2 ERROR: The input file does not exists. ; exit 1; }
TMPIN=$(mktemp)
# Remove blank lines and delete duplicates
sed '/^$/d' ""| sort -g | uniq > "$TMPIN"
NOW=$(date +"%Y-%m-%d-%X")
LOGFILE="AMU-log-$NOW.log"
for user in $(more "$TMPIN"); do
# Checks if the user already exists.
cut -d: -f1 /etc/passwd | grep "$user" > /dev/null
OUT=$?
if [ $OUT -eq 0 ];then
echo >&2 "ERROR: User account: \"$user\" already exists."
echo >&2 "ERROR: User account: \"$user\" already exists." >> "$LOGFILE"
else
# Create a new user
/usr/sbin/useradd -d "$PERS_HOME""$user" -s "$PERS_SH" -m "$user"
# passwdgen must be installed
pass=$(passwdgen -paq --length 8)
echo $pass | passwd --stdin $user
# save user and password in a file
echo -e $user"\t"$pass >> "$LOGFILE"
echo "The user \"$user\" has been created and has the password: $pass"
fi
done
rm -f "$TMPIN"
exit 0
else
echo >&2 "ERROR: You must be a root user to execute this script."
exit 1
fi
===========
============
Hope this helps.
希望这可以帮助。
Cheers, Carel
干杯,卡雷尔
回答by Paul S
I liked Tralemonkey's approach of echo thePassword | passwd theUsername --stdin
though it didn't quite work for me as written. This however worked for me.
我喜欢 Tralemonkey 的方法,echo thePassword | passwd theUsername --stdin
尽管它对我来说并不像所写的那样奏效。然而,这对我有用。
echo -e "$password\n$password\n" | sudo passwd $user
-e
is to recognize \n
as new line.
-e
是识别\n
为新行。
sudo
is root access for Ubuntu.
sudo
是 Ubuntu 的 root 访问权限。
The double quotes are to recognize $
and expand the variables.
双引号用于识别$
和扩展变量。
The above command passes the password and a new line, two times, to passwd
, which is what passwd
requires.
上面的命令将密码和一个新行两次传递给passwd
,这就是所passwd
需要的。
If not using variables, I think this probably works.
如果不使用变量,我认为这可能有效。
echo -e 'password\npassword\n' | sudo passwd username
Single quotes should suffice here.
单引号在这里就足够了。
回答by slm
Tralemonkey's solution almost worked for me as well ... but not quite. I ended up doing it this way:
Tralemonkey 的解决方案几乎对我也有效......但不完全如此。我最终这样做了:
echo -n '$#@password@#$' | passwd myusername --stdin
2 key details his solution didn't include, the -n
keeps echo from adding a \n
to the password that is getting encrypted, and the single quotes protect the contents from being interpreted by the shell (bash) in my case.
他的解决方案没有包括 2 个关键细节,在我的情况下,-n
保持回声不会\n
在加密的密码中添加 a ,并且单引号保护内容不被 shell (bash) 解释。
BTW I ran this command as root on a CentOS 5.6 system in case anyone is wondering.
顺便说一句,如果有人想知道,我在 CentOS 5.6 系统上以 root 身份运行此命令。
回答by Roger
--stdin
doesn't work on Debian. It says:
--stdin
在 Debian 上不起作用。它说:
`passwd: unrecognized option '--stdin'`
This worked for me:
这对我有用:
#useradd $USER
#echo "$USER:$SENHA" | chpasswd
Here we can find some other good ways:
在这里我们可以找到一些其他的好方法:
回答by SilverDaemon
回答by cevaris
The following works for me and tested on Ubuntu 14.04. It is a one liner that does not require any user input.
以下内容适用于我并在 Ubuntu 14.04 上进行了测试。它是一种不需要任何用户输入的单线。
sudo useradd -p $(openssl passwd -1 $PASS) $USERNAME
Taken from @Tralemonkey
取自@Tralemonkey