Can you delete all users but specified accounts in Ubuntu?

2

I am trying to find a way to quickly delete all user accounts except for the ones I specify in Ubuntu. Is there a good way of doing this? Perhaps a bash script that could do this function? I searched around and didn't really see anything.

I am doing this as a way to harden a system I am getting ready to take control over so I can remove all of the users except the ones I specify. There are several users.

Dylan

Posted 2014-05-05T00:05:33.353

Reputation: 113

Answers

2

Put the names of the accounts that you want to keep, one name per line, in the file keepers and run:

cut -d: -f1 /etc/passwd | grep -vFf keepers | while read name ; do deluser "$name" ; done

The above uses cut to get all the current user names from /etc/passwd. The command grep -vFf keepers removes from that list all names except the ones in listed keepers. Note that there are many system users that you will need to keep such as root, daemon, sys, mail, lp, etc. The do while loop deletes each name.

deluser has many options. See man deluser.

You might want to backup up your /etc/passwd, /etc/group, and other files before doing this just to be safe.

For the cautious, a two step approach

The first step creates a file with list of all accounts to be removed:

cut -d: -f1 /etc/passwd | grep -vFf keepers >goners

The file goners should be carefully inspected to assure that no important accounts are in it. It may be edited by hand if desired. Then run:

while read name ; do deluser "$name" ; done <goners

John1024

Posted 2014-05-05T00:05:33.353

Reputation: 13 893

Do NOT blindly run this script. Take a look at the list of users by just running cut -d: f1 /etc/passwd first - depending on the services your machine is running, deleting some of those accounts could wreck some of them. – Pockets – 2014-05-05T00:16:46.857

@SamuelLijin I am also totally opposed to running this "blindly". – John1024 – 2014-05-05T00:18:27.500