Manage Users in Linux
List Users and Groups
cat /etc/passwd
The file stores all users in the system in :
-seperated column format.
It has 7 fields starting from <username>
, whether password encrypted, user id <uid>
, group id <gid>
, comment
, home directory and shell.
cat /etc/group
The file contains group name, password, groud id <gid>
, and user names in this group.
id <username>
Shows the user id, group id and groups the person is in.
Modify Groups and Users
groupadd <groupname> # add a new group
groupmod -n <groupname> <old_groupname> # rename a group
useradd -m -c "First and Last Names" -G <groupname> -s <shell> <username>
usermod -aG <groupname> <username> # add a user to a group
gpasswd -d <username> <groupname> # remove a user from a group
Setup SSH for user
The following bash script creates .ssh
directory, takes the first argument from command line and puts it in authorized_keys
.
The trick is to run this script as the newly added user. So we need to put it somewhere everyone can run it, such as /usr/local/bin
and give it a name, say cpkey
.
Then, admin can sudo -u <username> /usr/local/bin/cpkey $(<cat pubkey>)
.
#! /bin/env bash
# create ssh folder and copy pub key
# before use this script, to create user and modify his group:
# useradd -m -c "<full name>" -s /bin/bash <username>
# usermod -aG <group> <username>
if [[ $# -eq 0 ]]
then
echo "please provide a pub key as the first argument."
echo "e.g. sudo -u <username> $0 \$(cat <pubkey-file>)"
exit 1
fi
mkdir -m 700 "$HOME"/.ssh
echo "$1" >"$HOME"/.ssh/authorized_keys
chmod 600 "$HOME"/.ssh/authorized_keys
Some ways to debug ssh failures. On the client side, ssh -vvv <remote_host>
. On the server side, check the authentication log.
tail -f /var/log/secure # rocky
tail -f /var/log/auth.log # ubuntu