Class 32: Linux User Inspection Commands Masterclass

Comprehensive Guide to Session Auditing, User Verification, Privilege Escalation & Inter-Terminal Messaging

Linux was architected from day one as a true multi-user, multi-tasking operating system. Multiple users can log in simultaneously via local physical virtual consoles (TTYs) or remote network SSH connections (pseudo-terminals PTS). For system administrators, monitoring who is logged into the machine, tracking their activities, auditing past session histories, and delegating administrative authority safely is essential for system security.

1. Current Identity Verification: whoami, id, and logname

When running automated scripts or multi-hop SSH sessions, knowing your exact current operating security context avoids devastating permission mistakes:

Command Primary Output Example Return
whoami Prints the effective username of the current execution context root or student
id Prints numeric UID, primary GID, all supplementary groups, and security context uid=1000(student) gid=1000(student) groups=1000(student),27(sudo)
logname Prints the original login username (even after executing sudo or su) student
# 1. Print effective username
whoami

# 2. View full numeric identity and group memberships
id

# 3. Print only the numeric UID (useful for bash scripts)
id -u
# Returns: 0 (if root) or 1000+ (for regular user)

# 4. Check if current user has sudo/wheel administrative permissions
id -nG | grep -E "(sudo|wheel)"

2. Active Logged-In User Tracking: who vs w

Linux provides two complementary utilities to inspect users currently connected to the server:

The 'who' Command

The who command reads the system /var/run/utmp database and prints one line per active session:

who -uH
# NAME     LINE         TIME             IDLE          PID COMMENT
# student  tty1         2026-11-02 08:30 .            1140 (:0)
# admin    pts/0        2026-11-02 09:15 00:14        2580 (192.168.1.50)
# devops   pts/1        2026-11-02 09:45 old          3412 (10.0.0.12)
  • -u: Lists idle time (. means actively typing; minutes:seconds; old means idle >24 hours) and session PID.
  • -H: Prints column header titles.
  • -b: Displays the exact time and date of the last system boot.

The 'w' Command: Comprehensive Activity Monitor

The w command combines uptime with detailed per-user activity analysis:

w
# 10:20:15 up 2 days,  3:45,  3 users,  load average: 0.15, 0.22, 0.18
# USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
# student  tty1     :0               08:30    1:50m  2:15   0.05s /usr/bin/gnome-session
# admin    pts/0    192.168.1.50     09:15    0.00s  0.12s  0.08s vim nginx.conf
# devops   pts/1    10.0.0.12        09:45   35:10   1.45s  1.40s python3 train.py
  • JCPU: Total CPU time consumed by all processes attached to this TTY/PTS session.
  • PCPU: CPU time consumed by the process currently running in the foreground (named under WHAT).
  • WHAT: The exact command line currently executing in the user's active session.

3. Session Auditing & History: last, lastb, and lastlog

Tracking past logins and failed brute-force attacks is the first step in security auditing:

Command Log Source File Auditing Purpose
last /var/log/wtmp Displays chronological history of successful logins, logouts, SSH IPs, and system reboots.
lastb /var/log/btmp Displays failed login attempts (critical for identifying SSH password guessing/brute force attacks; requires root).
lastlog /var/log/lastlog Scans every system account in /etc/passwd and reports the date, port, and IP of their most recent login.
# 1. View the last 5 system reboot events
last -x reboot | head -n 5

# 2. View login history for user 'admin'
last admin

# 3. View failed login attempts (requires sudo)
sudo lastb | head -n 10

# 4. View users who have never logged in
lastlog | grep "**Never logged in**"

4. Switching Users: su vs su - (The Crucial Difference)

The su command stands for substitute user (or switch user). Misunderstanding the difference between su and su - is one of the most frequent sources of permission and path errors in Linux administration:

Feature su user (Without Dash) su - user (With Dash / Login Shell)
Shell Type Non-login subshell Full login shell (executes /etc/profile & ~/.bash_profile)
Working Directory Stays in original user's directory Switches to target user's home directory (/root or /home/user)
Environment ($PATH, $HOME) Retains original user's environment and PATH variables Resets completely to target user's clean environment and administrative PATH (/sbin, /usr/sbin)
Best Practice Recommendation Avoid for system administration; risks polluting root environment Always recommended when switching to root or service users
# Correct way to open an interactive root shell:
su -

# Switch to database maintenance user with full environment:
su - postgres

5. Sudo Delegation: The Security Standard

Instead of sharing the root password across team members, modern Linux distributions utilize sudo (SuperUser DO). With sudo, authorized users execute administrative commands using their own individual password. Every sudo command is logged to /var/log/auth.log (Debian/Ubuntu) or /var/log/secure (RHEL/CentOS), providing non-repudiable audit trails.

The Golden Rule: Always Use visudo

The configuration file governing sudo permissions is /etc/sudoers. Never edit this file with nano or vi directly! Always edit it using sudo visudo. The visudo utility locks the file against concurrent edits and parses the entire file for syntax errors before saving. A syntax mistake in /etc/sudoers will lock out all sudo users instantly.

# Sudoers syntax structure:
# USER/GROUP    HOST=(RUNAS_USER:RUNAS_GROUP)    COMMANDS

# Example 1: Grant full unrestricted sudo privileges to user 'alex'
alex    ALL=(ALL:ALL) ALL

# Example 2: Allow user 'webadmin' to restart nginx without entering a password
webadmin ALL=(ALL) NOPASSWD: /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx

# Example 3: Refresh sudo timestamp (prompt for password again immediately)
sudo -k

6. Inter-Terminal Communication: wall & write

When multiple system operators or students are logged into a shared Linux server, administrators can broadcast messages directly across all terminal windows:

# 1. Broadcast server maintenance notice to ALL active terminals
wall "WARNING: Server will reboot for kernel updates in 15 minutes. Save your work."

# 2. Send a private one-on-one message to user 'admin' on pts/0
write admin pts/0
# Type message, then press Ctrl+D to send EOF

# 3. Prevent other non-root users from writing messages to your terminal
mesg n

# 4. Re-enable terminal message reception
mesg y

Student Practical Terminal Lab: User Inspection & Session Tracking

Terminal Lab Exercise: Execute the following command series in your terminal to inspect your current session context and examine system login history:

# Step 1: Verify your current user and UID
whoami
id

# Step 2: Check all active terminal sessions on the machine
who -H
w

# Step 3: Check system uptime and boot time
uptime -p
who -b

# Step 4: Inspect recent successful logins
last -n 5

# Step 5: Test mesg status
mesg

Viva Voce & Technical Interview Questions

who provides basic login details: username, terminal device (TTY/PTS), and login timestamp. w provides a comprehensive dashboard: system uptime, load averages, idle duration, CPU time consumed (JCPU/PCPU), and the current foreground process (WHAT) being executed by each user.
su retains the caller's environment variables, working directory, and non-administrative PATH, potentially executing user binaries instead of system tools. su - initializes a clean login environment, sets the root home directory (/root), and loads administrative system paths (/sbin, /usr/sbin).
whoami prints the effective user ID under which the current process runs (which changes to root when using sudo -s). logname prints the original user who authenticated at the terminal session initialization, unaffected by privilege elevation.
/etc/sudoers defines rules governing which users can run which commands as root or other users. visudo prevents concurrent conflicting edits through file locking and parses syntax errors before committing changes, preventing fatal configuration errors.
The last command reads the binary file /var/log/wtmp, which maintains an append-only log of all user logins, logouts, and system restart events.
lastb reads the /var/log/btmp file and displays failed login attempts. System administrators monitor it to detect dictionary and brute-force attacks against SSH or console ports.
wall stands for Write to ALL. It broadcasts a message to the terminal screens of all currently logged-in users, commonly used to warn users before an emergency shutdown or maintenance reboot.
TTY (TeleTYpewriter) represents a physical hardware console or Linux virtual terminal (e.g., tty1 to tty6 accessed via Ctrl+Alt+F1). PTS (Pseudo-Terminal Slave) represents a software-emulated terminal window (e.g. GNOME Terminal, xterm, or remote SSH connection).
Run sudo -k (kill timestamp). This invalidates the cached 15-minute credential ticket so that the next invocation of sudo requires re-entering the user password.
sudo -i provides a login environment shell for the target user (root by default) using sudo's own clean parameter initialization without spawning an unnecessary intermediate su process. It is considered cleaner and more idiomatic than sudo su.

Frequently Asked Questions (FAQs)

Run groups username or id username. For example, id www-data outputs the user ID, primary group, and supplementary groups for the web server user.
Find the user's PTS terminal number and session PID using who -u. Then terminate their login shell using: sudo kill -9 <PID>. Alternatively, use pkill -KILL -u username.
The user account has not been added to the administrative group (sudo on Ubuntu/Debian, or wheel on CentOS/RHEL/Fedora). Log in as root and run usermod -aG sudo username.
Use the -u flag: sudo -u username command. For example, to run database migrations as user postgres: sudo -u postgres psql.
utmp maintains the dynamic state of users currently logged in right now (read by who and w). wtmp is a permanent historical log of all past logins, logouts, and reboots (read by last).

Share this tutorial with fellow students & Linux learners:

Facebook Twitter LinkedIn