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
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