Sometimes in the initialization shell script you want to be able to create a user and specify a password, you can use the Useradd command to achieve this effect:
useradd -m -p encryptedPassword username
Parameter description:
- -M: Automatically set up the user's log in directory;
- -P Encryptedpassword: The return value of the encrypted password, method crypt ().
- Username user name to add
How to generate an encrypted password:
Use the Perl crypt () method to encrypt plaintext passwords, as shown in the following example:
$ perl -e ‘print crypt("password", "salt"),"\n"‘
The output is as follows:
sa3tHJ3/KuYvI
For the Useradd command need to use the encryption password, using ' password ' as salt, the specific syntax is as follows:
password="[email protected]"pass=$(perl‘print crypt($ARGV[0], "password")‘$password)echo$passpaU5t8Al/qf6M
The sample shell script is used to create the user:
adduser.sh
#!/bin/bash# Script to add a user to Linux systemif [ $(id -u) -eq 0 ]; then read -p "Enter username : " username read -s -p "Enter password : " password egrep "^$username" /etc/passwd >/dev/null if [ $? -eq 0 ]; then echo "$username exists!" exit 1 else pass=$(perl -e ‘print crypt($ARGV[0], "password")‘ $password) useradd -m -p $pass $username [ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!" fielse echo "Only root may add a user to the system" exit 2fi
Execute the script under the root user:
# ./adduser.shEnter username : rojaEnter password : HIDDENUser has been added to system!
Add the user's shell to your own use:
...#如果是生产环境,为了防止明文密码泄露,可以对shell脚本进行加密password="[email protected]"username="py"pass=$(perl -e ‘print crypt($ARGV[0], "password")‘ $password)useradd -m -p $pass $username...
Reference Links:
Https://www.cyberciti.biz/tips/howto-write-shell-script-to-add-user.html
Add a user and set a password in a shell script