Gabbo Gabbo - 2 months ago 19
Linux Question

How would I disable accounts that have been inactive for 90 days in Linux?

Working on a script that disables accounts that have been inactive for 90 days. Couldn't really find an answer after researching my problem for a few days, but I did find this command on a forum:

lastlog -t 10000 > temp1; lastlog -t 90 > temp2; diff temp1 temp2; rm temp1; rm temp2

This command outputs the users that have been inactive for 90 days. I think the solution to my problem would be to:

  1. Filter the output of this command so only the usernames are displayed (in a list, with 1 username per line).

  2. Take this output and write it to a text file.

  3. Run a for-loop that for each line in the file, the contents of the line (which should be just a single username) are stored in a variable called "inactiveUser". Then the command usermod -L $inactiveUser will be executed.

Would my proposed solution work? If so, how could it be achieved? Is there a much easier method to lock inactive accounts that I am not aware of?


you can simplify this with:

lastlog -b 90

which directly lists users who have not logged in in the past 90 days.

however, it also has a header row, and lists lots of system users.

use tail to skip the header row:

lastlog -b 90 | tail -n+2

then you could use grep to filter out system users:

lastlog -b 90 | tail -n+2 | grep -v 'Never log'

although perhaps there is a safer way to find real, non-system users, e.g.:

cd /home; find * -maxdepth 0 -type d

that issue aside, you can get just the usernames out with awk:

lastlog -b 90 | tail -n+2 | grep -v 'Never log' | awk '{print $1}'

then either output the list to a file, or else directly run usermod via while read loop or xargs:

lastlog -b 90 | tail -n+2 | grep -v 'Never log' | awk '{print $1}' |
  xargs -I{} usermod -L {}

perhaps you should also log what you've done:

lastlog -b 90 | tail -n+2 | grep -v 'Never log' | awk '{print $1}' |
  tee -a ~/usermod-L.log | xargs -I{} usermod -L {}