gpt4 book ai didi

bash - 如何在 Bash 脚本中创建新的用户名和密码?

转载 作者:行者123 更新时间:2023-11-29 09:42:09 25 4
gpt4 key购买 nike

我正在尝试创建一个脚本,在其中添加一个新的用户和密码,并在 Root 中运行时检查该用户和密码是否已经存在。

所以,我的脚本正在运行并且工作正常。它仅在根目录中运行,并且会正确检查用户名是否已被使用。但是,我似乎无法添加新用户和密码。以下是我的整个脚本:

#!/bin/bash
#Creating a script that creates a new user

ROOT_UID=0 #Root has $UID 0
SUCCESS=0
E_USEREXISTS=70
E_NOTROOT=65 #Not root

#Run as root, and this checks to see if the creater is in root. If not, will not run
if [ "$UID" -ne "$ROOT_UID" ]; then
echo "Sorry must be in root to run this script"
exit $E_NOTROOT
fi

if [ $# -eq 2 ]; then
username=$1
pass=$2

grep -q "$username" /etc/passwd

if [ $? -eq $SUCCESS ]; then
echo "User $username already exists"
echo "Please choose another username"
exit $E_USEREXISTS
fi

echo $pass | passwd $username --stdin
echo "the account is setup"

else
echo "this program needs 2 arguments and you have given $#"
echo "you have to call the script $0 username and the pass"
fi

exit 0

我并没有得到直接的错误,但这里有一个正在发生的事情的例子:我尝试添加某人(用户名,然后是密码):

[root@localhost Documents]# ./Script dkong 123bif

响应是:

passwd: Unknown user name 'dkong'
the account is setup

有人可以帮我指路吗?我希望它创建一个新的用户名和密码,但我不明白为什么不能。

我已经有一段时间没有使用脚本了,所以如果答案很明显,我很抱歉!只需要一点方向。提前致谢!

最佳答案

没关系!我成功了!这是我的解决方案:

useradd $username -d /home/$username -m ;
echo $passwd | passwd $username --stdin;
echo "the account is setup"

关于bash - 如何在 Bash 脚本中创建新的用户名和密码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48269919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com