Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script to get list of defined users on Linux?

Tags:

linux

bash

sed

awk

I put this together, but it sucks: (e.g. magic numbers in there, text parsing.. boo!)

awk -F: '{if($3 >= 1000 && $3 < 2**16-2) print $1}' /etc/passwd

What's the proper way to do this?

like image 687
Robottinosino Avatar asked May 19 '13 10:05

Robottinosino


2 Answers

Some unix systems don't use /etc/passwd, or have users that are not specified there. You should use getent passwd instead of reading /etc/passwd.

My system also has users that are disabled and can lo longer login with their login command set to /bin/false or /usr/sbin/nologin. You probably want to exclude them as well.

Here is what works for me including arheops awk command and ansgar's code to get the min and max from login.defs:

getent passwd | \
grep -vE '(nologin|false)$' | \
awk -F: -v min=`awk '/^UID_MIN/ {print $2}' /etc/login.defs` \
-v max=`awk '/^UID_MAX/ {print $2}' /etc/login.defs` \
'{if(($3 >= min)&&($3 <= max)) print $1}' | \
sort -u
like image 87
Stephen Ostermiller Avatar answered Nov 26 '22 11:11

Stephen Ostermiller


I am unsure why you do only > 1000, beacuase on redhat system it start from 500.

For me this awk script work ok:

awk -F: '{if(($3 >= 500)&&($3 <65534)) print $1}' /etc/passwd

Only uses with passwords:

awk -F: '{if(!(( $2 == "!!")||($2 == "*"))) print $1}' /etc/shadow 
like image 31
arheops Avatar answered Nov 26 '22 10:11

arheops