Re: [問題] 想寫一個command,搜尋group內member

作者: kenduest (小州)   2015-05-30 19:49:42
※ 引述《proud (hc)》之銘言:
: 想要寫一個commamd 來查詢某一group的user有誰
: 但不管用getgrnam() 或者是getgrnet() 都沒有辦法compiler
: 無法print出來
: 也想過給予gid 來搜尋, 但還是一直error
: 想請問這個問題點該怎麼解決?
: 謝謝大家
若不是使用 c 版本而是 shell script 參考看看。
#!/bin/bash
if [ "$#" -eq 1 ]; then
group_name="$1"
group_gid=$(cat /etc/group | grep "^$group_name:" | cut -d : -f 3)
members_in_group=$(echo "$itemlist" | cut -d : -f 4- | tr , " ")
echo -n "GroupName: $group_name, Members: $members_in_group "
user_list=$(grep "^.*:.*:.*:$group_gid:" /etc/passwd | cut -d : -f 1 | tr "\n" " ")
[ -n "user_list" ] && echo "$user_list"
else
for itemlist in $(cat /etc/group | grep -v "#")
do
group_name=$(echo "$itemlist" | cut -d : -f 1)
group_gid=$(echo "$itemlist" | cut -d : -f 3)
members_in_group=$(echo "$itemlist" | cut -d : -f 4- | tr , " ")
echo -n "GroupName: $group_name, Members: $members_in_group "
user_list=$(grep "^.*:.*:.*:$group_gid:" /etc/passwd | cut -d : -f 1 | tr "\n" " ")
[ -n "user_list" ] && echo "$user_list"
done
fi
跑起來效率不大好,尤其列出所有群組的成員清單時候....
另外提供一個 python 版本相同的功能:
#!/usr/bin/python
# coding: utf8
import sys
group_handle = open("/etc/group","r")
passwd_handle = open("/etc/passwd","r")
passwd_list = [ line.strip().split(":") for line in passwd_handle if line[0] != '#' ]
group_list = [ line.strip().split(":") for line in group_handle if line[0] != '#' ]
group_members = [ [line[0],line[1],line[2],line[3].split(",")] for line in group_list ]
for each_group_member in group_members :
for i in range(each_group_member[3].count('')) :
each_group_member[3].remove('')
for passwd_line_item in passwd_list :
for group_line_item in group_members :
if passwd_line_item[3] == group_line_item[2] and passwd_line_item[0] not in group_line_item[3] :
group_line_item[3].append(passwd_line_item[0])
################################################################################
if len(sys.argv) == 1 :
for line in group_members :
print("Group: %s, Members: %s" % (line[0], ",".join(line[3])))
else :
search_name = sys.argv[1]
for line in group_members :
if search_name == line[0]:
print("Group: %s, Members: %s" % (line[0], ",".join(line[3])))
python code 跑起來比較快.....
檔案下載:https://drive.google.com/file/d/0B1rfFnHqmPRLNGhqNFFLVlU0aVE/view?usp=sharing
ps: code 提供參考不一定保證都正確,謝謝

Links booklink

Contact Us: admin [ a t ] ucptt.com