gpt4 book ai didi

linux - 使用脚本更改用户的主要和次要组

转载 作者:太空宇宙 更新时间:2023-11-04 12:12:54 26 4
gpt4 key购买 nike

所以我想做的是运行一个只能从 Root 运行的脚本,它会创建新的用户名和密码。该脚本检查该用户名和密码是否已存在,如果存在,则不会创建新用户名。所有这些都很好,但是现在,如果创建了一个新用户,我希望能够将这个新用户添加到一个组中。

例如,假设我希望主要组为 alpha,次要组为 beta。我将如何能够:

  1. 将用户设置为主要组
  2. 将用户设置为主要和次要组
  3. 将用户设置为仅次要组

以下是我的脚本:

#!/bin/sh
# Creating a script that creates a new user and password, runs in Root, accessible # in any shell, ADD USER TO SPECIFIC GROUPS NOW (itar and bfe already created)

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
passwd=$2

grep -q "$username" /etc/passwd

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

#Creating the new username and the new password:
useradd $username -d /home/$username -m ;
echo $passwd | passwd $username --stdin;
echo "The new user account is setup"

#Adding the user to group bfe or itar
echo "Which group will this user be in?"
read x more

#If the person does not give the correct number of arguments
else
echo "This program needs 2 arguments and you have given $#"
echo "You have to call the script and provide a username and password"


#if [ \"$x\" -eq "bfe" ]; then #echo "First word was \"$x\""
# usermod -g bfe $username
#if [ \"$x\" -eq "itar" ]; then
# usermod -g itar $username

fi

exit 0

任何帮助将不胜感激!仍在学习绳索,所以请放轻松。

最佳答案

useradd 使用 -G 选项。

-G, --groups GROUP1[,GROUP2,...[,GROUPN]]]
A list of supplementary groups which the user is also a member of.Each
group is separated from the next by a comma, with no intervening
whitespace.
The groups are subject to the same restrictions
as the group given with the -g option.
The default is for the user to belong only
to the initial group.

然后重新安排你的部分脚本,像这样

#Adding the user to group bfe or itar
echo "Which group will this user be in?"
read x

# Check if group exists
grep -q "$x" /etc/group || echo "Group doesn't exist"

#Creating the new username and the new password:
useradd "$username" -d "/home/$username" -m -G "$x" ;
echo "$passwd" | passwd "$username" --stdin;
echo "The new user account is setup"

您可以使用-G 为用户分配多个组。

关于linux - 使用脚本更改用户的主要和次要组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48286222/

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