How to Log Every User Command to a Remote Syslog Server on Linux
This guide shows how to capture every command a Linux user runs, store it with timestamps, and forward the logs to a remote syslog server using shell configuration and rsyslog, offering two methods and discussing their limitations.
In a work environment you may need to record every command a user executes and send it to a log server. This article presents a simple solution that sends each command to the rsyslog daemon when the user logs out, and can be further configured to forward logs to a remote server via /etc/rsyslog.conf.
Method 1
# vi /etc/profile
# Set history format
export HISTTIMEFORMAT="[%Y-%m-%d %H:%M:%S] [`who am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`] "
# Record each shell command
export PROMPT_COMMAND='\
if [ -z "$OLD_PWD" ];then
export OLD_PWD=$PWD;
fi;
if [ ! -z "$LAST_CMD" ] && [ "$(history 1)" != "$LAST_CMD" ]; then
logger -t `whoami`_shell_cmd "[$OLD_PWD]$(history 1)";
fi ;
export LAST_CMD="$(history 1)";
export OLD_PWD=$PWD;'Method 2 (more cumbersome)
Step 1: Global settings (requires root)
# vi /etc/profile
# Set history format
export HISTTIMEFORMAT="[%Y-%m-%d %H:%M:%S] [`who am i 2>/dev/null| awk '{print $NF}'|sed -e 's/[()]//g'`] "
# Clear current history on login
echo "" > .bash_historyStep 2: Per‑user settings
# source /etc/profile
# vi /home/user1/.bash_logout
tmpfile="/tmp/`whoami`_history.tmp"
history > $tmpfile
k=1
while read line; do
((k++))
logger -t `whoami`_shell_cmd "$line"
done < $tmpfile
rm -f $tmpfileStep 3: Forward logs to a remote host (optional)
# vi /etc/rsyslog.conf
*.* @192.168.0.1Limitations:
Cannot record and send commands in real time.
Changes require a restart to capture commands from desktop terminals.
Original article, please retain the source link: http://www.wenwenyun.com/opration/shell/2015/0429/3686.html
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
