简体   繁体   中英

Why does python's os.stat() tell me my file group is empty?

I'm using python 2.6.4 on Solaris 5-10.

I have a file named "myFile". It is owned by someone else, by I ("myuser") am in the file's group ("mygrp"). Below is my python code. Why does it tell me that mygrp has no members???

>>> import os, pwd, grp 
>>> stat_info = os.stat("myFile") 
>>> fileUID = stat_info.st_uid 
>>> fileGID = stat_info.st_gid 
>>> fileGroup = grp.getgrgid(fileGID)[0] 
>>> fileUser = pwd.getpwuid(fileUID)[0] 
>>> print "grp.getgrgid(fileGID) = %s" % grp.getgrgid(fileGID) 
grp.getgrgid(fileGID) = grp.struct_group(gr_name='mygrp', gr_passwd='', gr_gid=100, gr_mem=[]) 

According to the docs (emphasis mine):

The gid is an integer, name and password are strings, and the member list is a list of strings. ( Note that most users are not explicitly listed as members of the group they are in according to the password database. Check both databases to get complete membership information. Also note that a gr_name that starts with a + or - is likely to be a YP/NIS reference and may not be accessible via getgrnam() or getgrgid().)

That might explain why you're not listed in the results, even though you're a member of that group. I believe you'd have to use pwd.getpwall and filter it for the group id to get the rest of the members of that group.

Update: Explaining further, according to the link the OP posted in the comments:

Every account has a primary group, and some accounts also have addtional groups. The primary group is the one in the .pw_gid attribute in the pwd entry. The additional groups are those that mention the account in the .gr_mem attribute in their grp entry.

Example code to retrieve all members of a group:

def all_members(gid):
    primary_members = [user.pw_name for user in pwd.getpwall() if user.pw_gid == gid]
    additional_members = grp.getgrgid(gid).gr_mem
    return primary_members + additional_members 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM