Search code examples
linuxterminalscriptingauditaudit-logging

Record actions on a terminal


I want to record actions that a user performs on a terminal. This includes actions that may be performed while the user may ssh to a remote host. It means that if a user runs

ssh user@192.168.1.1
user@192.168.1.1's password:

ls -ltr
f1 f2 f3

#record all the above

on a remote machine via ssh, it should record the command and the output. I am have written a bash script for it and have tried the following

while IFS="" read -e -d $'\n' -p "$USER@$HOSTNAME:$PWD$ " cmd; do 

This captures the input into cmd but how to trigger the command and record the output is still a mystery.

I am open to any other language if there is a better method.

If there is a way to select what gets recorded would be great as well. For example:

$ls
file1 file2 file3 folder1

#record

$cat file1
Lorem ipsum dolor sit amet, consectetur adipiscing elit

#do not record

Solution

  • Firstly, I'm assuming that with "actions that a user performs on a terminal" you mean keyboard input. This then matches the output which you also want to capture. This does not include e.g. the removal of a file when the user runs rm!

    Now, there is a misconception showing in your question. The terminal only provides input (from keyboard) and output (to the display). The input (apart from things it interprets itself) is then forwarded to a program, often a shell like e.g. zsh or fish while output from that program is forwarded to the display. This happens via the three standard streams stdin, stdout and stderr. What you basically need is a program that sits in between the terminal and the shell. This program marshals data between the terminal and the shell and at the same time records that data (or at least the output) to a file. This is e.g. what script does.

    Note that your requirement that SSH sessions are recorded is fulfilled as well. In the normal SSH session, the above chain with two elements (terminal, shell) is extended with the SSH client and remotely with an according SSH server process and another program (usually another shell). When you execute echo foo on the remote machine, the shell there outputs it to the SSH server process which then passes it to the SSH client, the local shell and finally the terminal for display. Input into the terminal takes the opposite path.