It had always been a common chore for me to hop in a update file permissions on a directory when a project changed hands or for any number of other reasons.

But this week, I was tasked with removing an entire user from the server. I know that Linux will handle the file ownership situation somewhat gracefully if I simply remove the user. Though, that just doesn’t seem very clean in my opinion.

I much preferred to reassign the permissions for that user to another user, then remove their account.

Reassigning the User

I started by having a look at the man pages for chown. Pretty straightforward if you make use of the –from flag.

chown --from=oldguy newguy * -R

Easy as pie right. So, let’s do the group. On most Linux servers that I’ve helped administer, if one user manages a directory solo, we also assign the directory to the primary group that is created for a user.

Here we go! Crap, there’s no –from available on the chgrp command. Now what?

Though I can’t imagine it, I’m sure there’s a pretty good reason for not providing a –from flag. It just seems to common an operation to overlook.

Reassigning the Group

Luckily, we can leverage Linux’s built-in find command to loop over files conditionally based on their group id.

Group id, what’s that? If you’re familiar with relational databases, you’re no doubt aware of how most records in a database have a numeric primary key to reference them. So, a users table might, for example contain three fields:

id, username, firstname, lastname

In the case of Linux, the same thing kinda happens under the hood. Except, only the id and username are stored.

To find the user id of a user or group id of a group, simple view the contents of the /etc/passwd or /etc/group files. You’ll likely need to have root privileges to do this.

cat /etc/passwd
cat /etc/group

We’re only concerned with the group id here, since the chown command made our lives easy. Once you know the group id, we’ll use the find command to loop over all files that are identified as being owned the specific group id you provide.

find . -gid 512 -exec chgrp newgroup {} +

That’s it!

As a final note, if you are removing a user completely, don’t forget to remove them from any groups in the /etc/group file, and also to remove their user account from the server.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *