~grouptree/grouptree/trunk

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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
#!/usr/bin/python
"""
Grouptree, a utility to maintain roles and "groups of groups"
on a POSIX system.

Copyright (C) 2008-2012 Malcolm Scott.

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Canonical homepage: http://launchpad.net/grouptree
"""

import ConfigParser, re, sys, spwd, grp, os

DEFAULT_CONFIG_FILE = "/etc/grouptree.cfg"

class CaseSensitiveConfigParser(ConfigParser.RawConfigParser):
	def optionxform(self, option):
		return str(option)

class GroupTreeException(Exception):
	def __init__(self, message):
		self.message = message
	def __str__(self):
		return self.message

def abort(msg="Aborted."):
	raise GroupTreeException(msg)

def validname(name):
	return bool(re.match('^[a-z0-9][-_.a-z0-9]*$', name))

def confirm(message):
	sys.stdout.write("Press Enter to %s, or Ctrl+C to exit. " % message)
	try:
		sys.stdin.readline()
	except KeyboardInterrupt:
		print
		abort()

def groupdiff(grnam, users, addcb=None, removecb=None, addgroupcb=None):
	try:
		groupentry = grp.getgrnam(grnam)
	except KeyError, e:
		if addgroupcb == None:
			raise e
		addgroupcb(grnam)
		currentmembers = []
	else:
		currentmembers = groupentry[3]
	if removecb != None:
		for m in currentmembers:
			if m not in users:
				removecb(grnam=grnam, user=m)
	if addcb != None:
		for u in users:
			if u not in currentmembers:
				addcb(grnam=grnam, user=u)

def shell(cmd, keywords=None):
	# Beware: assumes values in keywords are already escaped!
	for key, val in keywords.items():
		if cmd.find("%%%s%%" % key) != -1:
			cmd = cmd.replace("%%%s%%" % key, val)
		else:
			cmd += " %s" % val
	if os.spawnl(os.P_WAIT, "/bin/sh", "/bin/sh", "-c", cmd) != 0:
		abort("Uh oh!  Command '%s' failed!" % cmd)

def main(configfiles):
	config = CaseSensitiveConfigParser()
	readconfigs = config.read([DEFAULT_CONFIG_FILE] + configfiles)
	if len(readconfigs) == 0:
		abort("No valid configuration found.\n"
				"Create %s or provide the name of a configuration file."
				% DEFAULT_CONFIG_FILE)
	groups = {}
	nonexistentusers = []
	allusers = []
	cancelledusers = []
	for (role, people) in config.items('roles'):
		if not validname(role):
			abort("Role '%s' has an invalid name" % role)
		peoplelist = people.split()
		for person in peoplelist:
			if not validname(person):
				abort("User '%s' for role '%s' has an invalid name" % (person, role))
			if person not in allusers:
				allusers += [person]
			try:
				shadow = spwd.getspnam(person)
			except KeyError:
				if person not in nonexistentusers:
					nonexistentusers += [person]
			else:
				if shadow[7] >= 0 and person not in cancelledusers:
					cancelledusers += [person]
		groups[role] = peoplelist
	unresolvedgroups = {}
	wildcardgroup = None
	for (group, members) in config.items('groups'):
		if not validname(group):
			abort("Group '%s' has an invalid name" % group)
		if group in groups:
			abort("'%s' cannot be both role and group" % group)
		if members == "*":
			# special magic group containing everybody: when removing people from this group, disable account
			if wildcardgroup != None:
				abort("Cannot have more than one wildcard group.  Try '%s: %s' (or vice versa)." %
						(group, wildcardgroup))
			wildcardgroup = group
			groups[group] = allusers
		else:
			memberlist = members.split()
			unresolvedgroups[group] = memberlist
	progress = True
	while progress:
		progress = False
		for (group, members) in unresolvedgroups.items():
			if group not in groups:
				groups[group] = []
			done = []
			for member in members:
				if member in groups and member not in unresolvedgroups:
					for addition in groups[member]:
						if addition not in groups[group]:
							groups[group] += [addition]
					done += [member]
			if len(done) > 0:
				progress = True
				for member in done:
					unresolvedgroups[group].remove(member)
			if len(unresolvedgroups[group]) == 0:
				del unresolvedgroups[group]
	if len(unresolvedgroups) > 0:
		error = "Some groups unresolved:\n"
		for (group, members) in unresolvedgroups.items():
			error += "%s: %s\n" % (group, members)
		abort(error.rstrip())

	if len(nonexistentusers) > 0:
		print "Nonexistent users: %s" % " ".join(nonexistentusers)
		if not config.has_option('config', 'adduser'):
			abort("Cannot create users.  Deal with it yourself, or configure me.")
		confirm("go ahead and create accounts for these users")
		addusercmd = config.get('config', 'adduser')
		for user in nonexistentusers:
			shell(addusercmd, {'user':user})
		print

	if len(cancelledusers) > 0:
		print "Users who need uncancelling: %s" % " ".join(cancelledusers)
		if not config.has_option('config', 'reenableuser'):
			abort("Cannot uncancel users.  Deal with it yourself, or configure me.")
		confirm("go ahead and uncancel these users' accounts, and reissue passwords")
		uncancelusercmd = config.get('config', 'reenableuser')
		for user in cancelledusers:
			shell(uncancelusercmd, {'user':user})
		print

	# Assumption from here on: we don't care about primary groups, only supplementary groups.
	# This isn't a problem for additions (the user just ends up in the group twice).  It will
	# however fail to remove users from their primary groups.  Which is probably a good thing.

	# Start with the wildcard group cancellations, before we lose track of that group.
	if wildcardgroup != None:
		tocancel = []
		cancelcb = lambda grnam, user: tocancel.append(user)
		groupdiff(grnam=wildcardgroup, users=allusers, removecb=cancelcb)
		if len(tocancel) > 0:
			print "Users who should no longer be in group %s: %s" % (wildcardgroup, " ".join(tocancel))
			if not config.has_option('config', 'disableuser'):
				abort("Cannot cancel users.  Configure me.")
			confirm("go ahead and CANCEL these users' accounts")
			disableusercmd = config.get('config', 'disableuser')
			for user in tocancel:
				shell(disableusercmd, {'user':user})
			print

	if not config.has_option('config', 'addtogroup') or \
			not config.has_option('config', 'removefromgroup') or \
			not config.has_option('config', 'addgroup'):
		abort("Config missing addtogroup, removefromgroup and/or addgroup; can't do any more.")

	# Trial run of groupdiff; nothing actually changes yet
	changes = []
	addcb = lambda grnam, user: changes.append((grnam, "+%s" % user))
	removecb = lambda grnam, user: changes.append((grnam, "-%s" % user))
	addgroupcb = lambda grnam: changes.append((grnam, "new group:"))
	for (group, members) in groups.items():
		groupdiff(grnam=group, users=members, addcb=addcb, removecb=removecb, addgroupcb=addgroupcb)
	if len(changes) == 0:
		print "Groups are already up-to-date."
		sys.exit(0)
	prettychanges = {}
	for grnam, change in changes:
		if grnam not in prettychanges:
			prettychanges[grnam] = ''
		prettychanges[grnam] += ' ' + change
	print "Computed group changes:\n"
	for grnam, change in prettychanges.iteritems():
		print "%s:%s" % (grnam, change)
	print
	confirm("commit these changes")

	# Now run it again with callbacks that implement the changes
	addcb = lambda grnam, user: shell(config.get('config', 'addtogroup'), {'user':user, 'group':grnam})
	removecb = lambda grnam, user: shell(config.get('config', 'removefromgroup'), {'user':user, 'group':grnam})
	addgroupcb = lambda grnam: shell(config.get('config', 'addgroup'), {'group':grnam})
	for (group, members) in groups.items():
		groupdiff(grnam=group, users=members, addcb=addcb, removecb=removecb, addgroupcb=addgroupcb)

	print
	print "All done!"


if __name__ == "__main__":
	try:
		main(configfiles=sys.argv[1:])
	except GroupTreeException, e:
		print e
		sys.exit(1)