Skip to content

[Linux] How To List All Users

Last Updated on 2021-10-14 by Clay

When we are working on a remote Linux server, if we want to know how many users on this server, how do we list them?


List Users

Use cat command to print out /etc/passwd file

A simplest ideas is to print out /etc/passwd file, it is a file used to track every logged-in user who accessed the system.

The files contains the following information:

  • Username
  • User’s encryption password
  • User ID (UUID)
  • User Group ID (GID)
  • User’s full name (GECOS)
  • User home directory

And we can use cat command to print out:

cat /etc/passwd


Output:

But this format seems messy.

From the introduction of the /etc/passwd file above, we only need the username.


Use cut command to print out /etc/passwd username

Since only need the username, we can use cut command to do it.

Arguments explanation:

  • -d: Need to pass : as our separator
  • -f: Need to pass 1 to print out the first field separated
cut -d: -f1 /etc/passwd

Output:


Distinguish between System Users and Normal Users

Everyone must have noticed that root, daemon, bin.. etc. do not look like normal user names.

Yes, these are so-called system users, not normal users who created manually.

The more complicated way to distinguish is to use the getent command with UID_MIN and UID_MAX to find. Because the UIDs of system users and normal users are different.

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


Of course, we can add the cut command to make the output format cleaner.

eval getent passwd {$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)..$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)} | cut -d: -f1


Output:

I masked a few private account names

In this way, you can know which accounts exist on this server.


Use alias command to customize short instructions

But to be honest, this command is too long. It is recommended that you can write it in your ~/.bashrc configuration file to customize a new command lu.

To edit ~/.bashrc file:

vim ~/.bashrc


Add the following command:

alias lu = "eval getent passwd {$(awk '/^UID_MIN/ {print $2}' /etc/login.defs)..$(awk '/^UID_MAX/ {print $2}' /etc/login.defs)} | cut -d: -f1"


After saving and leaving, use source command to make the configuration effective.

source ~/.bashrc
lu


Output:

I masked a few private account names

Isn’t it convenient?


How many users are exist on the server

With the wc command, we can get how many users have been registered on this server. (In the example, I used the custom command lu)

lu | wc -l


Output:

16


This number is different for each server.

The above is about how to list users in Linux.


References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version