forked from maxgarvey/research_group_ownership
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ownership.py
92 lines (78 loc) · 3.2 KB
/
ownership.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import os
import grp
import logging
import pwd
import subprocess
from tempfile import TemporaryFile
def create_map(location='/vol/www/'):
'''create_map looks into the /vol/www directory and examines each item therein
entering each directory and getting the permissions of the files inside.'''
dir_dict = {}
#get all the permissions to bubble up just in case
location_asterisk = os.path.join(location,'*')
temp_fd = TemporaryFile()
subprocess.call(['ls -l '+location_asterisk], shell=True,
stdout = temp_fd, stderr=temp_fd)
temp_fd.close()
all_users_v = pwd.getpwall()
all_users = []
for user in all_users_v:
all_users.append(user[0])
#get a list of the contents of location... which will just be directories
dirs = os.listdir(location)
logging.debug('len(dirs): %d', len(dirs))
for _dir in dirs:
dir_dict[_dir] = {}
#for each of the directories inside of location,
for _dir in dirs:
#first try to get the permissions of the directory itself
try:
gid_number = os.stat(os.path.join(location, _dir)).st_gid
groupname = grp.getgrgid(gid_number)[0]
#print 'dir: ' + _dir + ', groupname: ' + groupname #debug
except Exception, err:
groupname = ''
logging.debug("couldn't stat: %s", os.path.join(location, _dir))
found_groupname = False
#if it is a proper groupname (not a user's group), keep it
try:
user = pwd.getpwnam(groupname)
except:
found_groupname = True
dir_dict[_dir] = groupname
#otherwise, look at the contents to figure out who the group is
if not found_groupname:
try:
#get the contents of that directory
dir_contents = os.listdir(os.path.join(location,_dir))
except Exception, err:
dir_contents = []
logging.debug("couldn't open: %s\n\t%s", os.path.join(location, _dir), str(err))
owners = {}
#for each of the items inside the directory
for subdir in dir_contents:
try:
#stat the file for gid
gid_number = os.stat(os.path.join(os.path.join(location,_dir),subdir)).st_gid
#and enter into our structure
if grp.getgrgid(gid_number)[0] in owners:
owners[grp.getgrgid(gid_number)[0]] += 1
else:
owners[grp.getgrgid(gid_number)[0]] = 1
except Exception, err:
logging.debug("couldn't stat: %s", os.path.join(location, _dir, subdir))
winner_number = 0
winner_owner = ''
for owner in owners.keys():
if owners[owner] > winner_number:
winner_owner = owner
winner_number = owners[owner]
dir_dict[_dir] = winner_owner
#remove empty elements
deleted_keys = []
for key in dir_dict.keys():
if dir_dict[key] == '':
deleted_keys.append(key)
del(dir_dict[key])
logging.debug('deleted keys: ', str(deleted_keys))
return dir_dict