Shell Script - every unique user

I have a homework: "for each unique user, let me know which group they are members of and when they last logged in"

So far I:

#!/bin/sh

echo "Your initial login:"
who | cut -d' ' -f1 | sort | uniq

echo "Now is logged:"
whoami

echo "Group ID:"
id -G $whoami

case $1 in
   "-l") last -Fn 10 | tr -s " " ;;
   *)    last -Fn 10 | tr -s " " | egrep -v '(^reboot)|(^$)|(^wtmp a)|(^ftp)' | cut -d" " -f1,5,7 | sort -uM | uniq -c
esac

My question is: how can I show each unique user? The script above shows only the later user logged in, but I need all the unique users.

Can anyone help?

+3
source share
4 answers

Script with last

#!/bin/bash
while read user; do
  echo "User '$user':"
  echo -e "\t Last login: $(last -1R "$user" | awk 'NR==1{if($0 ~ /^$/){print "Never"}else{$1=$2="";print}}')"
  echo -e "\t Groups: $(getent group | awk -F: -v user="$user" '$0 ~ user{a[i++]=$1} END{for(item in a)printf("%s ", a[item])}')"
done < <(getent passwd | awk -F: '{print $1}')

Output

Names changed to protect the innocent

User 'foo':
         Last login:  Oct 19 15:07:19 -0700 2010
         Groups: foo groupA groupB
User 'bar':
         Last login:  Nov 16 11:40:23 -0800 2008
         Groups: bar groupA groupC groupD
User 'baz':
         Last login: Never
         Groups: baz groupA groupD
0
source

The following link has several alternative ways to list users. They include reading /etc/passwd.

http://www.linuxquestions.org/linux/answers/Networking/How_to_list_all_your_USERs

0

, , /etc/passwd, :

$ for u in `cat /etc/passwd | cut -d: -f1`; do echo $u `id -Gn $u`; done
0
source

To iterate over any unique user, you can get the contents of the file passwdand get the first token of each line.

I would suggest using it getent passwdfor reading passwd, since it /etc/passwdcontains only users from local machine files (for example: there are no users from LDAP or other PAM plugins).

getent passwd | cut -d':' -f1

This command returns one user per line.

Then lastthey idtell you their last login and their group:

for user in `getent passwd | cut -d':' -f1`
do
    id ...
    last ...
done
0
source

Source: https://habr.com/ru/post/1784585/


All Articles