Just had to do a quick switch over of UID and GIDs for a couple of users.
I'm using Puppet to manage server configurations and it's got some nice features for automating the set-up of users. Unfortunately when I initially set-up the puppet directives, I overlooked setting the UID for each user which means that the UIDs assigned have been randomly created. As I want to maintain UIDs across all the boxes I'm using, it means there's a need to migrate users's uid's and gids that are different.
WARNING: Messing with UIDs and GIDs can be hazardous to your sanity if it all goes pear-shaped. Using any of the scripts that follow is done entirely at your own risk.
A bunch of commands to change UIDS and GIDS
Here's the commands to run as root to change the UID and GID for a user. Simply change the variables in angled brackets to match your settings:usermod -u <NEWUID> <LOGIN>
groupmod -g <NEWGID> <GROUP>
find / -user <OLDUID> -exec chown -h <NEWUID> {} \;
find / -group <OLDGID> -exec chgrp -h <NEWGID> {} \;
usermod -g <NEWGID> <LOGIN>
usermod
and groupmod
simply change the UID and GID for their respective named counterpart usermod
also changes the UID for the files in the homedir but naturally we can't assume the only place files have been created is in the user's homedir.
The find
command recurses the filesystem from / and changes everything with uid of OLDUID to be owned by NEWUID and them changes the group for the files owned by the OLDGROUP
The final usermod command changes the login group for the user
As Jared pointed out in the comments it's a good idea to specify -h for the chgrp and chown commands so that symlinks aren't followed. If anything that the symlink linked to is still owned by one of the users affected this will be sorted with the find commands anyway.
Swapping Users UIDs
In my case user bar had a UID of 1001 and user foo had a UID of 1002 and I wanted to swap them over. To do that you have to run the changes with an intermediate step or everything will get in a right pickle. So much so it would be the point in the film where the "real you" enters the room and tries to strangle you.- Change foo's UID and GID from 1001 -> 1012
- Change bar's UID and GID from 1002 -> 1011
- Change foo's UID and GID from 1012 -> 1002
- Change bar's UID and GID from 1011 -> 1001
These steps assume that 1012 and 1011 are not taken naturally.
There you have it. User foo now has a UID of 1002 and the foo group now has a GID of 1002 and user bar has a UID of 1001 and the group bar's GID is now 1001 too. Phew!