1

got the simple code below

USERS=`cat /etc/passwd`
for USER in $USERS
do
   echo "---------- $USER --------------"
   last -n 4 $USER
done

I want to ideally remove all users who haven't logged in for over 60 days.

But the problem with reading the /etc/passwd is that i get all of the system users as well.

Any ideas how to get just the user created accounts and remove them is they havent logged in for 90 days.

Cheers

2
  • 2
    If you are that concerned about active accounts, maintain your own database of users that are eligible for auto-deletion instead of relying on /etc/passwd.
    – chepner
    Mar 25, 2013 at 12:46
  • Check chage. With chage -l user you can info and with chage --something make users disable after XX days.
    – fedorqui
    Mar 25, 2013 at 13:05

2 Answers 2

3

Check if the UID is between UID_MIN and UID_MAX (defined in /etc/login.defs):

UID_MIN=$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)
UID_MAX=$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)

USERS=$(awk -F: -v min=$UID_MIN -v max=$UID_MAX '{
  if ($3 >= min && $3 <= max) print $1
}' /etc/passwd)

now=$(date +%s)

for user in $USERS; do
  last_login=$(date -d "$(last -FRn 1 $user |
    egrep -v "wtmp begins|still logged in" |
    awk '{print $10 " " $11 " " $13 " " $12}')" +%s)
  [ $(( (now - last_login) / 86400 )) -ge 90 ] && echo $user
done
3
  • All this does it list users? And for me it's listing the root user over and over again. Ideally i would like a shell script that i can add to cron which checks if a user has logged in within x days... if not delete them.
    – bsmoo
    Apr 2, 2013 at 15:53
  • Yes, all this does is list users. I don't recommend automatic deletion of user accounts. The reason why it was listing root over and over again was, because the part I had copy/pasted from your initial script echoed $USER (environment variable with the username of the currently logged-in user) instead of the loop variable $user. Variable names are case-sensitive. I updated my sample code so it prints only users that haven't logged in for 90 days or more. Apr 2, 2013 at 22:14
  • @ubuntu101010101 If you really do want to delete them automatically, you can simply change the echo command at the end to a deluser --remove-home command.
    – user370323
    Feb 10, 2016 at 18:35
0

Check the home directory of the user (6th column) and ignore those that are empty.

1
  • 1
    that will not work since service-users like named or lp have entries there and you do not want to delete them.
    – dwalter
    Mar 25, 2013 at 12:35

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .