bash 检查用户是否在组中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18431285/
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
Check if a user is in a group
提问by Gabi Barrientos
I have a server running where I use php to run a bash script to verify certain information of a user. For example, I have a webhosting server set up, and in order to be able to add another domain to their account I want to verify if the user is actually a member of the 'customers' group. What would be the best way to do this?
我有一台服务器在运行,我使用 php 运行 bash 脚本来验证用户的某些信息。例如,我设置了一个虚拟主机服务器,为了能够将另一个域添加到他们的帐户中,我想验证用户是否实际上是“客户”组的成员。什么是最好的方法来做到这一点?
I have searched google, but all it comes up with is ways to check whether a user or a group exists, so google is not being a big help right now.
我已经搜索过谷歌,但它提供的只是检查用户或组是否存在的方法,所以谷歌现在并没有太大帮助。
采纳答案by Gilles Quenot
Try doing this :
尝试这样做:
username=ANY_USERNAME
if getent group customers | grep -q "\b${username}\b"; then
echo true
else
echo false
fi
or
或者
username=ANY_USERNAME
if groups $username | grep -q '\bcustomers\b'; then
echo true
else
echo false
fi
回答by Antxon
if id -nG "$USER" | grep -qw "$GROUP"; then
echo $USER belongs to $GROUP
else
echo $USER does not belong to $GROUP
fi
Explanation:
解释:
id -nG $USER
shows the group names a user belongs to.grep -qw $GROUP
checks silently if $GROUP as a whole word is present in the input.
id -nG $USER
显示用户所属的组名。grep -qw $GROUP
静默检查输入中是否存在 $GROUP 作为整个单词。
回答by Nicholas Sushkin
A slightly more error-proof method to check for group membership using zero char delimited fixed string grep.
使用零字符分隔的固定字符串 grep 检查组成员身份的一种稍微防错的方法。
if id -nGz "$USER" | grep -qzxF "$GROUP"
then
echo User \`$USER\' belongs to group \`$GROUP\'
else
echo User \`$USER\' does not belong to group \`$GROUP\'
fi
or using long opts
或使用长选项
if id --name --groups --zero "$USER" |
grep --quiet --null-data --line-regexp --fixed-strings "$GROUP"
then
echo User \`$USER\' belongs to group \`$GROUP\'
else
echo User \`$USER\' does not belong to group \`$GROUP\'
fi
回答by cs2889
I know this is probably old thread but just in case this also works well:
我知道这可能是旧线程,但以防万一这也很好用:
id -Gn "username"|grep -c "groupname"
if any number > 0 is returned then user is a member of that group.
如果返回任何数字 > 0,则用户是该组的成员。
回答by odrac1r
You could use
groups $username_here | grep -q '\busergroup\b'
你可以用
groups $username_here | grep -q '\busergroup\b'
The exitcode will be 0 if a match was found, 1 if no match was found.
如果找到匹配项,退出代码将为 0,如果未找到匹配项,则退出代码将为 1。
user_in_group()
{
groups | grep -q "\b\b"
}
you could use this function as user_in_group userfoo groupbar
您可以将此功能用作 user_in_group userfoo groupbar
回答by Corin
For all those golffans out there:
对于所有的高尔夫球迷来说:
ingroup(){ [[ " "`id -Gn `" " == *" "* ]] }
Usage: ingroup group [user]
用法: ingroup group [user]
Example:
例子:
if ingroup video; then
echo 'Enjoy the show!'
fi
This solution uses groups
so it gets stung if the username is returned as part of its output, which it wasn't on my system, there's no accounting for taste! (Note that a user is often part of a group with the same name as the user, so it probably doesn't matter anyway.) You could try: [[ `id -Gn $2`" " == *" $1 "* ]]
which won't look at the first word in groups
s output. Anything more complicated than that and we'd be over par.
这个解决方案使用,groups
所以如果用户名作为其输出的一部分返回,它会被刺痛,它不在我的系统上,没有考虑品味!(请注意,用户通常是与该用户同名的组的一部分,因此无论如何它可能都无关紧要。)您可以尝试:[[ `id -Gn $2`" " == *" $1 "* ]]
它不会查看groups
s 输出中的第一个单词。任何比这更复杂的事情,我们都会超过标准杆。
TL;DR The point is I have taken advantage of the built in globbingin order to find the substring.
TL;DR 关键是我利用了内置的通配符来查找子字符串。
Edit: Thanks to @Anthony Geogheganfor the id -Gn
tip.
编辑:感谢@Anthony Geoghegan的id -Gn
提示。
回答by Aleks-Daniel Jakimenko-A.
Sounds like an another answer:
听起来像另一个答案:
username='myuser'
if grep -q -E "^customers:.*[:,]$username(,.*|\b)" /etc/group; then
echo 'true'
else
echo 'false'
fi
As reported by sputnick
the output of the groups
command may depend on your OS.
I am not sure how this code is going to perform, but most probably it will do better.
正如命令sputnick
输出所报告的那样,groups
可能取决于您的操作系统。我不确定这段代码将如何执行,但很可能它会做得更好。
回答by infomaniac
Using the zero delimiter to split by lines:
使用零分隔符按行拆分:
id -nGz user | tr 'is_in_group()
{
groupname=""
# The second argument is optional -- defaults to current user.
current_user="$(id -un)"
user="${2:-$current_user}"
for group in $(id -Gn "$user") ; do
if [ "$group" = "$groupname" ]; then
return 0
fi
done
# If it reaches this point, the user is not in the group.
return 1
}
' '\n' | grep '^group$'
回答by Anthony Geoghegan
A while ago, I wrote a shell function to check if a user is a member of a group. To maximise portability, I wanted it be POSIX-compatible (while this question is tagged as bash
, this function will still work). For performance, I wanted to use builtin shell features as much as possible: the only external command it uses is id
, the POSIX-standardised utility for getting data about a user's identity.
前段时间,我写了一个shell函数来检查一个用户是否是一个组的成员。为了最大限度地提高可移植性,我希望它与 POSIX 兼容(虽然这个问题被标记为bash
,但这个功能仍然有效)。为了提高性能,我想尽可能多地使用内置 shell 功能:它使用的唯一外部命令是id
POSIX 标准化实用程序,用于获取有关用户身份的数据。
g=mail
userlist="anthony postfix xxx"
for u in $userlist; do
if is_in_group "$g" "$u"; then
printf "%s is in ‘%s'\n" "$u" "$g"
else
printf "%s is NOT in ‘%s'\n" "$u" "$g"
fi
done
Example usage to test both positive and negative cases – and ensure it handles a non-existent username gracefully:
测试正面和负面案例的示例用法 - 并确保它优雅地处理不存在的用户名:
anthony is NOT in ‘mail'
postfix is in ‘mail'
id: ‘xxx': no such user
xxx is NOT in ‘mail'
Running the above command prints the following output:
运行上述命令会打印以下输出:
[[ " $(groups) " =~ ' spark ' ]] && echo 'Is in group'
It hasn't been tested for the case where a group or user has a space or other unusual characters in their name but some research shows that such names are not legal: the POSIX Base Definition for Group Namestates that
尚未针对群组或用户的名称中包含空格或其他异常字符的情况进行测试,但一些研究表明此类名称是不合法的:群组名称的 POSIX 基本定义指出
To be portable across conforming systems, the value is composed of characters from the portable filename character set.
为了在符合标准的系统之间可移植,该值由可移植文件名字符集中的字符组成。
The Portable Filename Character Setis specified as the alphanumeric characters, A-Z, a-z, 0-9 along with the period, underscore, and hyphen-minus characters.
的可移植文件名字符集被指定为字母数字字符,AZ,AZ,0-9与周期,下划线,和连字符减号字符一起。
回答by fdb
Bash single line:
Bash 单行:
if [[ " $(groups) " =~ ' spark ' ]]; then
echo 'Is in group'
fi
Bash multi line:
Bash 多行:
##代码##