How to Log All User Shell Commands in Linux with Timestamp, TTY, and IP – Per User Logging

This guide explains how to comprehensively log all shell commands executed by Linux users, maintaining separate log files per user with detailed information such as timestamps, TTY, and IP address. This approach enhances auditing, security, and troubleshooting by providing clear, user-specific activity records.

The solution ensures logging starts automatically on user login and persists through system reboots. It supports multiple concurrent users, capturing each user’s commands independently without impacting system performance.

Step-by-Step: Secure User Shell Command Logging

🛠 1. Create a Central Logging Directory

sudo mkdir -p /var/log/user_cmd_logs
sudo chmod 750 /var/log/user_cmd_logs
sudo chown root:root /var/log/user_cmd_logs

🧾 2. Create the Logging Script

Create this script to be run at every user login:

sudo nano /etc/profile.d/user_command_logger.sh

Paste the following:

#!/bin/bash

# Capture IP and TTY
TTY=$(tty)
IP=$(who -u am i 2>/dev/null | awk '{print $NF}' | tr -d '()')
[ -z "$IP" ] && IP="local"

# Set log path
LOG_DIR="/var/log/user_cmd_logs"
LOG_FILE="${LOG_DIR}/${USER}.log"

# Create log file if not exists
touch "$LOG_FILE"
chown root:root "$LOG_FILE"
chmod 600 "$LOG_FILE"

# Set environment for timestamped logging
export PROMPT_COMMAND='history -a >(awk -v ip="$IP" -v tty="$TTY" -v user="$USER" -v ts="$(date +%F\ %T)" '"'"'{print ts " | " user " | " tty " | " ip " | " $0}'"'"' >> "$LOG_FILE")'

Make it executable:

sudo chmod +x /etc/profile.d/user_command_logger.sh

🔒 3. Lock Log Files (Optional: Prevent Deletion or Tampering)

sudo chattr +a /var/log/user_cmd_logs/*.log

This sets append-only mode—users can’t modify or delete logs, even as root (unless chattr -a is run first).

🔁 4. Auto-Run at Reboot (Already Handled via /etc/profile.d/)

This script automatically runs when users start a shell session. You do not need crontab or rc.local for this.

🔍 5. Test the Logging

Log in as different users (e.g., via SSH or su).

Run commands like ls, whoami, pwd.

Then view logs:

sudo cat /var/log/user_cmd_logs/username.log

📦 Sample Log Output

2025-05-30 14:51:20 | john | /dev/pts/0 | 192.168.1.22 | ls -la
2025-05-30 14:51:23 | john | /dev/pts/0 | 192.168.1.22 | whoami