首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bash脚本,对于给定的组名,打印所有用户和他们所在的组,包括给定的组。

Bash脚本,对于给定的组名,打印所有用户和他们所在的组,包括给定的组。
EN

Stack Overflow用户
提问于 2021-01-28 15:13:59
回答 2查看 640关注 0票数 0

我正在创建一个以组名命名的脚本,它应该打印所有用户和他们所在的组,包括给定的用户和组,但我仍然想不出如何正确地这样做,下面是我的代码:

代码语言:javascript
复制
#!/bin/bash

# contentFile is the file you are trying to read
# contentFile will be a parameter supplied by the user
# thus we leave it empty for now
groupName=

## List of options the program will accept;
## those options that take arguments are followed by a colon
## in this case, group name: n
optstring=n:

## The loop calls getopts until there are no more options on the command line
## Each option is stored in $opt, any option arguments are stored in OPTARG
while getopts $optstring opt
do
    case $opt in
        n) groupName=$OPTARG ;; ## $OPTARG contains the argument to the option (contentFile in this context)
        *) exit 1 ;; ## exit if anything else other than -f file name was entered
    esac
done

groups=$(cat /etc/group | cut -d: -f1)

for user in $(cat /etc/passwd  | cut -d: -f1)
do 
    echo grep -q $groupName $groups
    if [ $? = 0  ]
    then
        echo "- grupuri:" "$user" "\n;"
    fi
done

我得到的输出

代码语言:javascript
复制
grep -q root adm wheel kmem tty utmp audio disk input kvm lp optical render storage uucp video users sys mem ftp mail log smmsp proc games lock network floppy scanner power systemd-journal rfkill nobody dbus bin daemon http systemd-journal-remote systemd-network systemd-resolve systemd-timesync systemd-coredump uuidd dnsmasq rpc gdm ntp avahi colord cups flatpak geoclue git nm-openconnect nm-openvpn polkitd rtkit usbmux fsociety postgres locate mongodb dhcpcd docker openvpn mysql
  • grupuri: mysql \n;

预期产出:

代码语言:javascript
复制
whoopsie - grupuri:whoopsie;
colord - grupuri:colord;
sssd - grupuri:sssd;
geoclue - grupuri:geoclue;
pulse - grupuri:audio;pulse;pulse-access;

我们非常感谢你的帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2021-01-28 15:34:02

考虑下面的bash脚本;

代码语言:javascript
复制
group='certuser'
for user in $(awk -F ':' "/${group}/"'{print $4}' /etc/group | tr ',' '\n'); do
    echo "$(groups $user)"
done

哪里

  1. awk -F ':' '/certuser/ { print $4 }' /etc/group 获取$group ('certuser')组中的每个用户,由,分隔。 使用awk删除组信息,因此我们只保留用户
  2. | tr ',' '\n' 将csv发送到for-循环的管道。
  3. echo "$(groups $user)" 使用groups命令获取该组中的所有用户
票数 2
EN

Stack Overflow用户

发布于 2021-01-28 15:37:58

使用getent命令检索有关组和用户的信息。特别是,getent group查询组,而getent passwd查询用户。

代码语言:javascript
复制
#! /bin/bash
group=$1
gid=$(getent group "$1" | cut -d: -f3)
getent passwd \
| awk -F: -v gid=$gid '($4==gid){print $1}' \
| xargs -n1 groups
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65939946

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档