Knowledge

Exercise: shell startup files over SSH and command logging

Updated 2026-11-08 · Present

Estimated time: 45 minutes.

This exercise has two closely linked parts:

  1. The startup mechanism: when you ssh into a Linux machine, which files get executed, and in what order? Distinguish login shell, non-login shell, interactive vs non-interactive, and the role of PAM before the shell runs.
  2. Command Logging (cmd-log): configure rsyslog (facility local6) to record every command a user types into /var/log/cmdlog.log as JSON (time, user, PID, command, exit code, client IP). This is exactly why part 1 matters: put the configuration in the wrong file → the shell never loads it → nothing gets logged.

Lab server: 192.0.2.21 (hostname dattqh-nat, Ubuntu 24.04). The IP addresses in this exercise are illustrative addresses from the range reserved for documentation (RFC 5737: 192.0.2.0/24, 198.51.100.0/24); when you do the lab, replace them with the real IPs of your machines. Requirement: be able to explain the file order for each type of shell, then install cmd-log for real and verify that the log appears.

Step 1 — Tell the 4 kinds of shell apart

Bash decides which files to load based on two axes: login/non-login and interactive/non-interactive. ssh <USER>@<HOST> (with a TTY) = login + interactive; bash/tmux/su/a subshell = non-login + interactive; ssh <USER>@<HOST> "command" or running a .sh script = non-interactive.

shopt login_shell   # on = login shell
echo "$-"           # contains i = interactive

Note: Check right in your own session: $- contains i when the shell is interactive.

Step 2 — File order on SSH login (login shell)

Bash reads files in this order: /etc/profile → (if interactive) /etc/bash.bashrc → /etc/profile.d/*.sh → then the FIRST personal file that exists among ~/.bash_profile › ~/.bash_login › ~/.profile. On Ubuntu, ~/.profile in turn does source ~/.bashrc.

grep -n "bash.bashrc\|profile.d" /etc/profile
grep -n "bashrc" ~/.profile

Note: Only the first existing personal file is read — if ~/.bash_profile exists, ~/.profile is ignored. This is the classic configuration mistake behind PATH/variables "disappearing".

Step 3 — Non-login interactive

(opening a child bash, tmux, su): reads only /etc/bash.bashrc + ~/.bashrc (specific to the Debian/Ubuntu patch — SYS_BASHRC). Non-interactive (ssh host "cmd", scripts): reads NO startup file at all, unless the BASH_ENV variable points to one.

Note: Consequence: commands run through ssh host "cmd", cron, or CI do NOT get the PATH/aliases of a login session — and the PROMPT_COMMAND-based cmd-log does not run in these sessions either.

Step 4 — PAM runs before the shell

sshd calls the PAM stack (/etc/pam.d/sshd); pam_env loads /etc/environment and /etc/security/pam_env.conf (environment variables, the system PATH), and pam_motd prints the banner. These variables apply to every kind of login (including non-interactive) because they are set before bash reads profile/bashrc.

cat /etc/environment
grep -R "pam_env\|pam_motd" /etc/pam.d/sshd /etc/pam.d/login

Note: That is why a PATH set in /etc/environment is always there, while a PATH set in ~/.bashrc only exists in interactive shells.

Step 5 — Verify with strace

instead of guessing: list exactly which files bash opens (openat) at startup — no file needs to be modified.

# Login shell (like an SSH login):
strace -f -e trace=openat bash -il -c true 2>&1 | grep -E "profile|bashrc" | grep -v ENOENT
# Non-login interactive (child bash):
strace -f -e trace=openat bash -i  -c true 2>&1 | grep -E "profile|bashrc" | grep -v ENOENT

Note: Compare the two lists to see exactly the difference between login and non-login.

Step 6 — Why does cmd-log go in `~/.bashrc` & `/etc/bash.bashrc`?

The cmd-log mechanism relies on the PROMPT_COMMAND variable — bash runs it before every prompt of an interactive shell. So it must live in a file that interactive shells load: /etc/bash.bashrc (system-wide, Debian/Ubuntu), /etc/bashrc (RedHat), /root/.bashrc (root), and /etc/skel/.bashrc (users created later).

Note: Putting it in /etc/profile would only catch login shells and miss every child shell → use bash.bashrc/bashrc to cover all interactive sessions.

Step 7 — rsyslog routing

send facility local6 to its own file /var/log/cmdlog.log, creating the file in advance with the owner that rsyslog writes as.

On Ubuntu, rsyslog drops privileges to the syslog user ($PrivDropToUser syslog) and creates log files with $FileOwner syslog, $FileGroup adm, $FileCreateMode 0640 (in /etc/rsyslog.conf), so a file created by hand must be handed back to syslog:adm:

# --- Ubuntu ---
echo "local6.* /var/log/cmdlog.log" | sudo tee -a /etc/rsyslog.d/50-default.conf
sudo touch /var/log/cmdlog.log
sudo chown syslog:adm /var/log/cmdlog.log && sudo chmod 0640 /var/log/cmdlog.log
sudo systemctl restart rsyslog

On RHEL / CentOS / Rocky, rsyslog runs as root and there is no syslog user (the chown syslog:... command would report invalid user). The rule goes in /etc/rsyslog.conf, and the file stays root:root with mode 0600:

# --- RHEL / CentOS / Rocky ---
echo "local6.* /var/log/cmdlog.log" | sudo tee -a /etc/rsyslog.conf
sudo touch /var/log/cmdlog.log && sudo chmod 0600 /var/log/cmdlog.log
sudo systemctl restart rsyslog

Note: On each distro, declare the local6.* rule in only one place; declaring it in two places makes every command get written twice (see step 12).

Step 8 — Load the PROMPT_COMMAND block (cmd-log)

Write the following block into the system-wide bashrc file. It takes the client IP from ${SSH_CLIENT%% *} (a variable sshd sets for you) and, at every prompt, emits one JSON line via logger -p local6.debug (time, user, PID, the command taken from HISTTIMEFORMAT= history 1, exit code, IP).

Ubuntu: every interactive shell (root included) reads /etc/bash.bashrc, so writing it here is enough.

# --- Ubuntu ---
sudo tee -a /etc/bash.bashrc >/dev/null <<'EOF'
# Command log — each interactive command emits one JSON line via logger local6.debug
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "{\"log_type\": \"cmdlog\", \"time_cli\": \"$(date "+%d/%m/%y %T")\", \"user\": \"$(whoami)\", \"shell_pid\": \"$$\", \"command\": \"$(HISTTIMEFORMAT= history 1 | sed "s/^ *[0-9]* *//")\", \"return_value\": \"$RETRN_VAL\", \"client_ip\": \"${SSH_CLIENT%% *}\"}"'
export HISTTIMEFORMAT="%d/%m/%y %T "
EOF

On RedHat, use /etc/bashrc instead of /etc/bash.bashrc (bash on RHEL does not read this file by itself; every user's default ~/.bashrc, root included, does source /etc/bashrc):

# --- RHEL / CentOS / Rocky ---
sudo tee -a /etc/bashrc >/dev/null <<'EOF'
# Command log — each interactive command emits one JSON line via logger local6.debug
export PROMPT_COMMAND='RETRN_VAL=$?;logger -p local6.debug "{\"log_type\": \"cmdlog\", \"time_cli\": \"$(date "+%d/%m/%y %T")\", \"user\": \"$(whoami)\", \"shell_pid\": \"$$\", \"command\": \"$(HISTTIMEFORMAT= history 1 | sed "s/^ *[0-9]* *//")\", \"return_value\": \"$RETRN_VAL\", \"client_ip\": \"${SSH_CLIENT%% *}\"}"'
export HISTTIMEFORMAT="%d/%m/%y %T "
EOF

Note: To apply it to the current session right away: source /etc/bash.bashrc (RHEL: source /etc/bashrc), then type any command. The block here fixes 2 bugs in the original Notion script on Ubuntu 24.04 (see Illustrations 6–7). For the full OS-auto-detecting script (root + existing users + new users): see the Notion page under References.

Step 9 — HISTTIMEFORMAT is already in the step 8 block

(%d/%m/%y %T) so that history shows the date and time. The key point: because it is enabled, the part of PROMPT_COMMAND that fetches the command must use HISTTIMEFORMAT= history 1 (disabled locally) — otherwise the command field gets a timestamp stuck onto it (see Illustration 6).

Step 10 — Log rotation

so that /var/log/cmdlog.log does not grow without bound.

sudo tee /etc/logrotate.d/cmdlog >/dev/null <<'EOF'
/var/log/cmdlog.log {
  size 100M
  rotate 4
  create
  dateext
  compress
}
EOF

Step 11 — (Optional) Forward logs to a central server

Send all logs over to the central log server using the RFC5424 format.

IP_SERVER='192.0.2.30:514'   # central log server
echo "*.*  @$IP_SERVER;RSYSLOG_SyslogProtocol23Format" | sudo tee -a /etc/rsyslog.conf
sudo systemctl restart rsyslog

Note: One @ = UDP, two @@ = TCP. The example above uses UDP.

Step 12 — Handle duplicate log lines

If every command is written as 2 lines → there is a duplicate local6/cmd rule in /etc/rsyslog.d.

cd /etc/rsyslog.d && grep -Rin "cmd\|local6" .
# Comment out/delete the extra line (usually in 50-default.conf), then:
sudo systemctl restart rsyslog

Illustration 1 — Non-interactive

ssh host "cmd" is NOT a login and NOT interactive → no startup file is loaded.

ssh <USER>@192.0.2.21 'shopt login_shell; echo "flags=$-"; echo "PS1=${PS1:-unset}"'

Result:

login_shell    off
flags=hBc
PS1=unset

Note: The missing i flag ⇒ the PROMPT_COMMAND-based cmd-log does not run with this way of invoking the shell.

Illustration 2 — Interactive SSH login (with a TTY) = login shell

The order in which files are actually opened (strace openat) — note that /etc/bash.bashrc appears because the session is interactive.

strace -f -e trace=openat bash -il -c true 2>&1 | grep -E "profile|bashrc" | grep -v ENOENT

Result:

openat(AT_FDCWD, "/etc/profile", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/bash.bashrc", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/profile.d/01-locale-fix.sh", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/profile.d/apps-bin-path.sh", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/profile.d/bash_completion.sh", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/profile.d/gawk.sh", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/profile.d/Z97-byobu.sh", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/profile.d/Z99-cloudinit-warnings.sh", O_RDONLY) = 3
openat(AT_FDCWD, "/etc/profile.d/Z99-cloud-locale-test.sh", O_RDONLY) = 3
openat(AT_FDCWD, "/home/dattqh-nat/.profile", O_RDONLY) = 3
openat(AT_FDCWD, "/home/dattqh-nat/.bashrc", O_RDONLY) = 3

Note: In the same session: login_shell on, $- = himBHc (contains i).

Illustration 3 — Interactive, not login

(opening a child bash / tmux / su) → only 2 files; all of /etc/profile* and ~/.profile are skipped.

strace -f -e trace=openat bash -i -c true 2>&1 | grep -E "profile|bashrc" | grep -v ENOENT

Result:

openat(AT_FDCWD, "/etc/bash.bashrc", O_RDONLY) = 3
openat(AT_FDCWD, "/home/dattqh-nat/.bashrc", O_RDONLY) = 3

Note: This is the Debian/Ubuntu patch (SYS_BASHRC) — upstream bash does not read /etc/bash.bashrc by itself.

Illustration 4 — The "first existing file" rule

This machine has neither ~/.bash_profile nor ~/.bash_login, so bash falls through to ~/.profile.

for f in ~/.bash_profile ~/.bash_login ~/.profile; do [ -e "$f" ] && echo "EXISTS: $f" || echo "absent: $f"; done

Result:

absent: /home/dattqh-nat/.bash_profile
absent: /home/dattqh-nat/.bash_login
EXISTS: /home/dattqh-nat/.profile

Illustration 5 — The underlying mechanism of cmd-log

emit a test JSON line through logger into facility local6, then read it back from journald — this proves the command→syslog path before PROMPT_COMMAND is installed.

logger -t CMDLOGTEST -p local6.debug '{"log_type":"cmdlog","user":"dattqh-nat","command":"echo demo","return_value":"0","client_ip":"probe"}'
journalctl -t CMDLOGTEST --no-pager -n 1 -o short-iso

Result:

2026-07-02T03:15:26+00:00 dattqh-nat CMDLOGTEST[195351]: {"log_type": "cmdlog", "user": "dattqh-nat", "command": "echo demo", "return_value": "0", "client_ip": "probe"}

Note: On a machine where it is not yet installed, there is no dedicated local6 rule, so this line lands in /var/log/syslog; only step 7 splits it off into /var/log/cmdlog.log.

Illustration 6 — Pitfall: the original Notion script logs wrongly in 2 places on Ubuntu 24.04

When HISTTIMEFORMAT is enabled, history 1 prints the date and time too, so command gets a timestamp stuck onto it; and who am i | awk '{print $5}' picks the wrong column, so client_ip comes out as a time.

tail -n 1 /var/log/cmdlog.log

Result:

...: {"log_type": "cmdlog", "time_cli": "02/07/26 03:55:20", "user": "dattqh-nat", "shell_pid": "195696", "command": "02/07/26 03:55:20 echo ai-verify-cmdlog", "return_value": "0", "client_ip": "03:55"}

Note: REAL output on dattqh-nat with the original script — command has 02/07/26 03:55:20 stuck on, and client_ip=03:55 (wrong).

Illustration 7 — After the fix (the version used in step 8)

fetch the command with HISTTIMEFORMAT= history 1 (timestamp disabled locally) and client_ip from ${SSH_CLIENT%% *} (a variable sshd sets for you) → the log is clean and correct.

tail -n 1 /var/log/cmdlog.log

Result:

...: {"log_type": "cmdlog", "time_cli": "02/07/26 03:59:59", "user": "dattqh-nat", "shell_pid": "196053", "command": "echo fix-verify-OK", "return_value": "0", "client_ip": "198.51.100.10"}

Note: REAL output on dattqh-nat after the fix — command is clean, client_ip=198.51.100.10 (the correct IP of the machine that SSHed in).

References