Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- import sh
- import re
- HUMANS = ['jkane', 'djames', 'mkirk']
- def clean_passwd(h, humans):
- clean = []
- for row in h:
- user = row.split(':')
- if user[0] not in humans:
- clean.append(row.strip())
- else:
- print('Removing %r' % user[0])
- return "\n".join(clean) + "\n"
- def clean_group(h, humans):
- clean = []
- for row in h:
- group = row.split(':')
- users = group[-1].split(',')
- new_users = []
- for user in users:
- user = user.strip()
- if user not in humans:
- new_users.append(user)
- else:
- print('Removing %r from group %r' % (user, group[0]))
- group[-1] = ",".join(new_users)
- if group[0] not in humans:
- clean.append(':'.join(group))
- else:
- print('Removing group %r' % group[0])
- return "\n".join(clean) + "\n"
- def clean_shadow(h, humans):
- """format of /etc/shadow is close-enough to password for our purposes"""
- return clean_passwd(h, humans)
- for human in HUMANS:
- try:
- uid, gid, groups = sh.id(human).split()
- except sh.ErrorReturnCode_1:
- print('Human %r not found.' % human)
- continue
- old_uid = int(re.search("uid=(\d*)\(.*", uid).group(1))
- old_gid = int(re.search("gid=(\d*)\(.*", gid).group(1))
- print("Human %r was uid %r / gid %r" % (human, old_uid, old_gid))
- with open('/etc/passwd', 'r') as h:
- clean = clean_passwd(h, [human])
- with open('/etc/passwd', 'w') as h:
- h.write(clean)
- with open('/etc/group', 'r') as h:
- clean = clean_group(h, [human])
- with open('/etc/group', 'w') as h:
- h.write(clean)
- with open('/etc/shadow', 'r') as h:
- clean = clean_shadow(h, [human])
- with open('/etc/shadow', 'w') as h:
- h.write(clean)
- try:
- uid, gid, groups = sh.id(human).split()
- except sh.ErrorReturnCode_1:
- print('Human %r not found.' % human)
- continue
- new_uid = int(re.search("uid=(\d*)\(.*", uid).group(1))
- new_gid = int(re.search("gid=(\d*)\(.*", gid).group(1))
- print("Human %r is now uid %r / gid %r" % (human, new_uid, new_gid))
- if new_uid != old_uid:
- # change every file owned by old_uid to be owned by this human
- sh.find("/", "-uid", old_uid, "-exec", "chown", human, "{}", "+")
- if new_gid != old_gid:
- # change every file owned by old_gid to be owned by the new group
- # the -h is to avoid reaching through symlinks and instead change the sym itself
- sh.find("/", "-gid", old_gid, "-exec", "chgrp", "-h", new_gid, "{}", "+")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement