Linux – Dump users and group membership to file

groupslinuxoracleusers

I'm trying to get an oracle 6.2 system (same as redhat 6.2) to find all the users on the system, then take the username of each user discovered and query group membership of each user individually, and output to a file once a month, so I need to write the command as a shell script and schedule

I'm pretty new to Linux, and there seems to be many ways to call users and group memberships. I am currently using the below to output a list of users to file.

getent passwd >> /home/username/users.txt

I don't really know what to do next. The output always puts the username first, so I would like to grep the file for the first word of every line, and run

getent group | grep %

where % is the first word of every line, and to repeat that process until the end of the file is reached, then stop, and dump the output to a network location (windows share) that would be \windowsserver\share\usersandgroups.csv so I can open the file in excel, and hopefully have the username in cell A1, followed by each group in their own cells (B1, C1, D1 etc) with each user on a new row. If getent isn't ideal for this, can anyone suggest a command that'll do the job? I need the users and groups names as opposed to ID's.

I don't necessarily need to output the users to a file, so if that step can be avoided, that would be useful.

Thanks to anyone that can help.

Best Answer

Here's a one liner:

getent passwd | awk -F ':' {'print $1'} | xargs -I {}  groups {} | sed 's/ : /:/g' | tr ' ' ','

This dumps straight to console like so:

pulse:pulse
shearn89:shearn89,apache,monit,wireshark

UPDATE: To get this in 'pure' .csv format, you could use this:

getent passwd | awk -F ':' {'print $1'} | xargs -I {}  groups {} | sed 's/ : /,/g' | tr ' ' ','

This would give you user,group1,group2,group3, so for users who are only in 'their' group, you'd get pulse,pulse (for example).