Check user and group in linux

Check if a user is in a group

I have a server running where I use php to run a bash script to verify certain information of a user. For example, I have a webhosting server set up, and in order to be able to add another domain to their account I want to verify if the user is actually a member of the ‘customers’ group. What would be the best way to do this? I have searched google, but all it comes up with is ways to check whether a user or a group exists, so google is not being a big help right now.

16 Answers 16

if id -nG "$USER" | grep -qw "$GROUP"; then echo $USER belongs to $GROUP else echo $USER does not belong to $GROUP fi 
  1. id -nG $USER shows the group names a user belongs to.
  2. grep -qw $GROUP checks silently if $GROUP as a whole word is present in the input.

grep -qw doesn’t work as expected for group names with — character. systemd-journal for example, matches journal or systemd .

username=ANY_USERNAME if getent group customers | grep -q "\b$\b"; then echo true else echo false fi 
username=ANY_USERNAME if groups $username | grep -q '\bcustomers\b'; then echo true else echo false fi 

This script has a bug in it! If the username is customers but it does not belong to customers group your script will still return true!

We don’t have the same output on our distros. I use archlinux and the same behaviour have been saw on debian likes distro.

Username appears in the groups command output at the output beginning, before a : . This can be avoid by using id -Gn instead. Also, The word boundary \b can be avoid by using -w flag in grep, and the output redirection to /dev/null can be removed by using -q to specify silent check: grep will only return success or failure exit code to the shell this way.

This is flawed. Group/user names can contain — and this character (as far as -b is concerned) does separate words. \bcustomers\b matches non-customers or customers-data .

A slightly more error-proof method to check for group membership using zero char delimited fixed string grep.

if id -nGz "$USER" | grep -qzxF "$GROUP" then echo User \`$USER\' belongs to group \`$GROUP\' else echo User \`$USER\' does not belong to group \`$GROUP\' fi 
if id --name --groups --zero "$USER" | grep --quiet --null-data --line-regexp --fixed-strings "$GROUP" then echo User \`$USER\' belongs to group \`$GROUP\' else echo User \`$USER\' does not belong to group \`$GROUP\' fi 

This one may cause problems if you have two groups with similar names, eg. sales and salessupport . Asking about sales with match both.

Читайте также:  Test serial port in linux

@ralphbolton No, the problem you described won’t happen. -x ensures that sales matches only exactly that and not salessupport .

I know this is probably old thread but just in case this also works well:

id -Gn "username"|grep -c "groupname" 

if any number > 0 is returned then user is a member of that group.

You could use groups $username_here | grep -q ‘\busergroup\b’

The exitcode will be 0 if a match was found, 1 if no match was found.

you could use this function as user_in_group userfoo groupbar

Why echo $? ? A shell function returns the exit code from the last executed command automatically. Also, the &>/dev/null can be avoided by using -q in grep.

For all those golf fans out there:

if ingroup video; then echo 'Enjoy the show!' fi 

TL;DR The point is I have taken advantage of the built in globbing in order to find the substring.

Edit: Thanks to @Anthony Geoghegan for the id -Gn tip.

My own answer goes in the opposite direction (portability, verbosity, and readability) but I love the brevity and cleverness of this answer. To avoid worrying about the output of the groups command, you could replace it with the more predictable (and portable) id -Gn . It’s also one character shorter. 🙂

Great answer in terms of real world usage. This check is safe, portable, and efficient, though you might want to use [[ » $(id -Gn — «$2″) » == *» $1 «* ]] to protect against non-usernames in $2 . In terms of golf, it isn’t that great. id -Gnz $2|grep -qxz $1 would be 10 bytes shorter.

And yet there’s space to grow! If you’re using set -u in your shell scripts, this command will fail if you don’t set the (supposedly optional) user parameter. We use POSIX parameter expansion to fix this oversight: [[ » `id -Gn $<2->` » == *» $1 «* ]] .

Using the zero delimiter to split by lines:

id -nGz user | tr '\0' '\n' | grep '^group$' 

This one seems to work with all weird permutations of groups with — in them, groups with similar names etc. To use the GROUP variable like other answers, you can write it like this id -nGz user | tr ‘\0’ ‘\n’ | grep ‘^’$‘$’ and can get rid of the output (to use just the return code, $? ) by using grep -q .

A while ago, I wrote a shell function to check if a user is a member of a group. To maximise portability, I wanted it be POSIX-compatible (while this question is tagged as bash , this function will still work). For performance, I wanted to use builtin shell features as much as possible: the only external command it uses is id , the POSIX-standardised utility for getting data about a user’s identity.

is_in_group() < groupname="$1" # The second argument is optional -- defaults to current user. current_user="$(id -un)" user="$" for group in $(id -Gn "$user") ; do if [ "$group" = "$groupname" ]; then return 0 fi done # If it reaches this point, the user is not in the group. return 1 > 

Example usage to test both positive and negative cases – and ensure it handles a non-existent username gracefully:

g=mail userlist="anthony postfix xxx" for u in $userlist; do if is_in_group "$g" "$u"; then printf "%s is in ‘%s’\n" "$u" "$g" else printf "%s is NOT in ‘%s’\n" "$u" "$g" fi done 

Running the above command prints the following output:

anthony is NOT in ‘mail’ postfix is in ‘mail’ id: ‘xxx’: no such user xxx is NOT in ‘mail’ 

It hasn’t been tested for the case where a group or user has a space or other unusual characters in their name but some research shows that such names are not legal: the POSIX Base Definition for Group Name states that

To be portable across conforming systems, the value is composed of characters from the portable filename character set.

The Portable Filename Character Set is specified as the alphanumeric characters, A-Z, a-z, 0-9 along with the period, underscore, and hyphen-minus characters.

Читайте также:  Kali linux запустить network manager

Источник

12 Ways to Find User Account Info and Login Details in Linux

This article will show you useful ways to find information about users on a Linux system. Here we’ll describe commands to get a user’s account details, show login details as well what users are doing on the system.

If you want to add or create users in Linux, use the useradd command, and to modify or change any attributes of an already created user account, use the usermod command via the command line.

You might also like:

We’ll start by looking at 12 useful commands to find a user’s account information, then proceed to explain commands to view login details in the Linux system.

1. id Command – Show User and Group IDs

The id is a simple command line utility for displaying a real and effective user and group IDs identity information for the current user or specified user.

View User and Group ID

2. groups Command – View User Group Memberships

The groups command is used to display the group memberships for a user. It lists all the groups that a user belongs to, including both primary and supplementary groups.

Check User Groups in Linux

3. finger Command – Show User Information

The finger command is used to search for information about a user on Linux, which includes detailed information about a specific user or a list of users, including their login name, real name, terminal, idle time, login time, and other relevant details.

The finger command doesn’t come pre-installed on many Linux distributions, you need to install it using your default package manager as shown.

$ sudo apt install finger [On Debian, Ubuntu and Mint] $ sudo yum install finger [On RHEL/CentOS/Fedora and Rocky/AlmaLinux] $ sudo emerge -a sys-apps/finger [On Gentoo Linux] $ sudo apk add finger [On Alpine Linux] $ sudo pacman -S finger [On Arch Linux] $ sudo zypper install finger [On OpenSUSE]

It shows a user’s real name; home directory; shell; login: name, time; and so much more as shown below.

Check User Info in Linux

4. getent Command – Fetch User Info from System Database

The getent command is used to retrieve information from various databases, including the system user and group databases. It can be used to retrieve information about users, groups, hosts, networks, protocols, and other system entities that are stored in database files like /etc/passwd, /etc/group, /etc/hosts, etc.

To get a user’s account details, use the passwd database and the username as follows.

Fetch User Info in Linux

5. grep Command – Search for Patterns or Specific Text in Files

The grep command is a powerful command used to search for patterns or specific text in files. It allows you to filter and extract lines from text based on matching patterns. The name “grep” stands for “Global Regular Expression Print“.

You might also like:

You can use grep to find information about a specific user from the system accounts file: /etc/passwd as shown below.

Grep - Fetch User Info in Linux

6. lslogins Command – Display User Information in Linux

The lslogins command shows information about known users in the system, which typically includes details such as the username, UID (User ID), GID (Group ID), home directory, shell, last login time, and more, depending on the options used and the system configuration.

$ lslogins -u tecmint $ lslogins -u

Display User Info in Linux

7. users Command – List Current Logged-In Users on Linux

The users command is used to display the list of currently logged-in users on the Linux system.

Читайте также:  Linux update dynamic dns

Show Current Logged in Users in Linux

8. who Command – Show Information Of Currently Logged-In Users

The who command is used to display users who are logged on to the system, including the username, terminal, login time, and remote host from which the user is logged in.

Show Current Logged in Users

9. w Command – Show Currently Logged-In User Activity

The w command shows a summary of the currently logged-in users and their activity, which displays the login session, including the username, terminal, login time, idle time, JCPU (total CPU time used by all processes), PCPU (CPU time used by the current process), and the command or process running on the terminal.

Show Currently Logged-In User Activity

10. last Command – Show Most Recent Login Session

The last command displays a list of the most recent login sessions, which includes information about the users who have logged in, their login times, and the terminals or remote hosts they used for login.

Show Most Recent Login Sessions

To show all the users who were present at a specified time, use the -p option as follows.

List Most Recent User Logins

11. lastb Command – Show Failed Login Attempts

The lastb command is used to display a list of the last failed login attempts on the system. It reads from the system log file that records failed login attempts, typically stored in /var/log/btmp.

Show Failed Login Attempts in Linux

12. lastlog Command – List User Login Information

lastlog command is used to find the details of the most recent login information for all users or a specific user on the system, which provides details about the last login time and location for each user.

$ lastlog OR $ lastlog -u tecmint

List User Login Information

That’s it! If you know any other command-line trick or command to view user account details do share with us.

You might also like:

In this article, we’ve explained various ways to find information about users and login details on a Linux system. You can ask any questions or share your thoughts via the feedback form below.

Источник

How to find out what group a given user has?

This appears to be pretty useful as well. It has more verbose output than the ‘groups’ command, so if you need the group id/user id use this!

On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:

which is equivalent to groups [user] utility which has been obsoleted on Unix.

On OS X/Unix, the command id -p [user] is suggested for normal interactive.

Explanation on the parameters:

-G , —groups — print all group IDs

-n , —name — print a name instead of a number, for -ugG

-p — Make the output human-readable.

or just study /etc/groups (ok this does probably not work if it uses pam with ldap)

Below is the script which is integrated into ansible and generating dashboard in CSV format.

sh collection.sh #!/bin/bash HOSTNAME=`hostname -s` for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt sudo cat /etc/sudoers| grep -v "^#"|awk ''|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt 

My output stored in below text files.

cat /tmp/ANSIBLENODE_sudo.txt cat /tmp/ANSIBLENODE_inventory.txt cat /tmp/ANSIBLENODE_inventory_users.txt 

Источник

Оцените статью
Adblock
detector