linux shell historical command logging

  • 2020-05-10 23:19:03
  • OfStack

Under Linux you can use the history command to view all of the user's historical actions, while the shell command action records are kept by default in the.bash_history file in the user directory. Through this file, you can query the execution history of shell command, which is helpful for operation and maintenance personnel to conduct system audit and problem troubleshooting. At the same time, after the server is attacked by hackers, you can also query the historical command operation of the hacker logging into the server. However, the hacker will delete the.bash_history file in order to erase the trace after the intrusion, which requires a reasonable backup of this file.

The default history command can only view the user's history, but it can't tell when each user acted on the command. This is quite inconvenient for problem troubleshooting. The solution is to add the following four lines to the /etc/bashrc file so that the history command automatically records the execution time of all shell commands:


HISTFILESIZE=4000
HISTSIZE=4000
HISTTIMEFORMAT='%F %T'
export HISTTIMEFORMAT

HISTFILESIZE represents the total number of records saved in the command in the.bash_history file. The default value is 1000. HISTSIZE defines the total number of records output from the history command; HISTTIMEFORMAT defines the time display format, which is the same as "+"%F %T" after the date command. HISTTIMEFORMAT passes the value to the history command as the time variable of history.

Advanced techniques

Although the above one can record the time, it cannot be used for audit purposes and can be easily tampered with or lost by hackers. The following method details the user who logged into the system, the IP address, the shell command, and the time of the detailed operation. This information will be kept in a secure place in the form of a file for system audit and troubleshooting.

You can do this by putting the following code into the /etc/profile file.


#Record history operation
USER_IP=`who -u am i 2>/dev/null |awk '{print $NF}' |sed -e 's/[()]//g'`
LOGNAME=`who -u am i |awk '{print $1}'`
HISTDIR=/user/share/.history
if [ -z $USER_IP]
then
    USER_IP=`hostname`
fi if [ ! -d $HISTDIR]
then
    mkdir -p $HISTDIR
    chmod 777 $HISTDIR
fi if [ ! -d $HISTDIR/${LOGNAME}]
then
    mkdir -p $HISTDIR/${LOGNAME}
    chmod 300 $HISTDIR/${LOGNAME}
fi export HISTSIZE=4000 DT=`date +"%Y%m%d_%H%M%S"`
export HISTFILE="$HISTDIR/${LOGNAME}/${USER_IP}.history.$DT"
export HISTTIMEFORMAT="[%Y.%m.%d %H:%M:%S]"
chmod 600 $HISTDIR/${LOGNAME}/*.history* 2>/dev/null

  resources
  • < < The high-performance Linux server was built in the real world -- system security, troubleshooting, automated operations and maintenance, and cluster architecture > > The book


Related articles: