简体   繁体   中英

How to log every single command executed from shell script

I am trying to find a way to record every single command that is executed by any user on the system. Things that I have came across earlier.

  1. It is possible to view shell commands executed from the terminal using ~/.bashrc_history file.

There is a catch here, It logs only those commands which were executed interactively from bash shell/terminal.

This solves one of my problems. But in addition to it, I would like to log those commands also which were executed as a part of the shell script.

Note: I don't have control over shell script. Therefore, adding verbose mode like

#!/bin/bash -xe
is not possible.

However, this can be assumed that I have root access as a system administrator.

Eg: I have another user that has access to the system. And he runs the following shell script using from his account.

 #./bin/sh nmap google.com

and run as "$ sh script.sh"

Now, What I want is "nmap google.com" command should be logged somewhere once this file is executed.

Thanks in advance. Even a small help is appreciated.

Edit: I would like to clarify that users are unaware that they are being monitored. So I need a solution something at system level(may be agent running with root). I cannot depend on user to log suspicious activity. Of-course everyone will avoid such tricks to put blame on someone else if they do something fishy or wrong

You can run the script in this way:

  • execute bash (it will override the shebang)
  • ts to prefix every lines
  • logs both in terminal and files

bash -x script.sh |& ts | tee -a /tmp/$(date +%F).log

You may ask the other user to create an alias.

Edit: You may also add this into /etc/profile (sourced when users login)

exec > >(tee -a /tmp/$(date +%F).log)

Do it also for error output if needed. Keep it splited.

I am aware that you were asking for Bash and Shell scripting and tagged your question accordingly, but in respect to your requirements

  • Record every single command that is executed by any user on the system
  • Users are unaware that they are being monitored
  • A solution something at system level

I am under the assumption that you are looking for Audit Logging .

So you may take advantage from articles like

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM