The method of logging and sending executed commands to the server in Linux

Time:2020-10-1

In the work, it is necessary to record every command executed by the user and send it to the log server. Therefore, I have made a simple solution. This scheme will send every command executed by the user to the log daemon rsyslogd when each user logs out of the login. You can also configure the / etc/ rsyslog.conf ”The log is further sent to the log server

The first method

Copy code

The code is as follows:

# vi /etc/profile
#Format history
export HISTTIMEFORMAT=”[%Y-%m-%d %H:%M:%S] [`who am i 2>/dev/null| \
awk ‘{print $NF}’|sed -e ‘s/[()]//g’`] “
#Record every command executed by the shell
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;’

The second method
Step 1: global settings (this is a one-time setting and requires root privileges)

Copy code

The code is as follows:

# vi /etc/profile
#Execute this script when the user logs in
#Format history display
export HISTTIMEFORMAT=”[%Y-%m-%d %H:%M:%S] [`who am i 2>/dev/null\
| awk ‘{print $NF}’|sed -e ‘s/[()]//g’`] “
#Clear current cache echo “>. Bash at login_ history

Step 2: set different users separately

Copy code

The code is as follows:

# source /etc/profile
# vi /home/user1/.bash_logout
#This script is executed when the user logs off
tmpfile=”/tmp/`whoami`_history.tmp”
#Record the formatted history in a file
history > $tmpfile
#Read the file and send the contents of the file line by line to syslogd.
#Don’t try to replace the following code with “history | logger” or “logger – f $tmpfile.”,
#Otherwise, only the first 200 lines will be recorded.
k=1
while read line; do
((k++))
logger -t `whoami`_shell_cmd “$line”
done < $tmpfile
rm -f $tmpfile

(repeat the second step if there are other users to monitor)
Step 3: send the log to the remote host (optional)

Copy code

The code is as follows:

# vi /etc/rsyslog.conf
#Add such as downlink, IP change itself, you can also use domain name, @ means UDP protocol, @ @ means TCP protocol
*.* @192.168.0.1

 
deficiencies:
1. Unable to record commands and send logs in real time
2. To record the commands under the terminal desktop, you need to restart.
=========

20151218113647294.png (914×409)