Linux Security Tip — Contextualizing Executed Commands History

The Big F.
2 min readMar 17, 2022

By default, the UNIX/ Linux systems maintain a record of commands executed by the users during the current session using the history. Linux history is handy for users and administrators who don’t like retyping their commands. It is also handy when recalling infrequently used commands.

Linux history is a good source of information, but in scenarios where you need to attribute commands executed to the responsible user with the timestamp and remote source address — the default history entries lack the contextual information you need. I faced this challenge in the recent past, and I tasked myself to seek options to improve this powerful command recorder in Linux.

Follow this simple instruction to enhance your history entries:

(1) Add a custom script in “/etc/profile.d/” to enable this enhancements for all login users. On your favourite shell editor:

  • sudo touch /etc/profile.d/ehistory.sh
  • sudo chmod +x /etc/profile.d/ehistory.sh
  • sudo vi /etc/profile.d/ehistory.sh.

(2) Append the following line to the “ehistory.sh” file and save:

# Enhanced Linux History.
# Author: Samuel Fabeyo (The Big F.)
# Reference: https://github.com/fabeyor/ehistory

HISTTIMEFORMAT=”TimeStamp: %m/%d/%Y %H:%M | SrcIP: $(w | grep -Eo ‘(^| )(([0–9]|[1–9][0–9]|1[0–9]{2}|2[0–4][0–9]|25[0–5])\.){3}([0–9]|[1–9][0–9]|1[0–9]{2}|2[0–4][0–9]|25[0–5])($|[[:space:]])’) | Logon User: $USER | Command: “

(3) Load the updated source file to implement the enhancements OR Logout and Login OR reboot the system:

  • sudo source /etc/profile.d/ehistory.sh

Explanation: The above-added entry will display the remote source network address, responsible user, timestamp and the command executed per entry. Sample output would look something like the image below:

And that’s as simple as it gets…

Possible Issue and Fix:

When clone or copy the content of the script, you might find it does now give the desired result. This is usually due to how quotation marks or some special characters are transcribed when ported from one system to another.

  • If you experience this, just rewrite all the Quotation Marks and Apostrophes(i.e “ “, ‘ ‘, ‘). and reload the script.

--

--

The Big F.

The personification of the phrase: " The quieter you are, the more you are able to hear." I like sharing knowledge and learning to add to it.