我无法完全理解 newgrp 的功能。它是否有助于从一个组移动到另一个特定用户所属的组。或者它允许成为用户不是成员但有组密码的组的成员。我对此不太清楚。你们中有人能给我一个清晰的解释吗?
答案1
要理解该newgrp
命令的作用,您需要了解,当您将用户添加到组时,新用户实际上不会添加到该组,直到您注销并重新登录。这通常很麻烦,因为它会杀死您的所有程序。newgrp
允许您将用户添加到组并使其在当前登录会话中生效。
用法
# show groups user "ubuntu" belongs to
ubuntu@ubuntu:/usr/share/man$ groups ubuntu
ubuntu : ubuntu adm cdrom sudo dip plugdev lpadmin sambashare
# add user "ubuntu" to group: src
ubuntu@ubuntu:/usr/share/man$ sudo gpasswd -a ubuntu src
Adding user ubuntu to group src
ubuntu@ubuntu:/usr/share/man$ groups ubuntu
ubuntu : ubuntu adm cdrom sudo dip src plugdev lpadmin sambashare
# ^^^
# user ubuntu is "technically" now added to group `src`
# now try do something that members of `src` can do
# i.e. create a file in /usr/local/src/
ubuntu@ubuntu:/usr/share/man$ ls -alh /usr/local/
total 0
drwxr-xr-x 1 root root 100 Jul 20 08:42 .
drwxr-xr-x 1 root root 180 Dec 2 20:19 ..
drwxr-xr-x 1 root root 80 Dec 2 20:15 bin
drwxr-xr-x 2 root root 3 Jul 20 08:42 etc
drwxr-xr-x 2 root root 3 Jul 20 08:42 games
drwxr-xr-x 2 root root 3 Jul 20 08:42 include
drwxr-xr-x 4 root root 49 Jul 20 08:45 lib
lrwxrwxrwx 1 root root 9 Jul 20 08:42 man -> share/man
drwxr-xr-x 2 root root 3 Jul 20 08:42 sbin
drwxr-xr-x 1 root root 60 Dec 2 19:53 share
drwxrwxr-x 1 root src 60 Dec 2 19:55 src
ubuntu@ubuntu:/usr/share/man$ touch /usr/local/src/a_file
touch: cannot touch '/usr/local/src/a_file': Permission denied
# it doesn't work
# now run "newgrp" on src group
ubuntu@ubuntu:/usr/share/man$ newgrp src
ubuntu@ubuntu:/usr/share/man$ touch /usr/local/src/a_file
# now you are truly part of src group
ubuntu@ubuntu:/usr/share/man$ ls -alh /usr/local/src
total 0
drwxrwxr-x 1 root src 80 Dec 2 21:26 .
drwxr-xr-x 1 root root 100 Jul 20 08:42 ..
-rw-rw-r-- 1 ubuntu src 0 Dec 2 21:26 a_file
答案2
newgrp
运行一个 shell,将其真实组 ID(请参阅man 7 credentials
)设置为请求的组,该组可以是用户所属的组之一,也可以是用户知道密码的组。(组可以像用户帐户一样拥有密码。)
返回到newgrp
使用exit
终止执行的 shell之前的情况newgrp
。由于newgrp
运行的是新 shell,因此在脚本中使用它时需要小心(提示:将命令导入其中,或使用此处文档)。