0

I need to re-setup history command to show both date, time and the IP address of user's from where they logged in to our server and execute a particular command. Is there any way to show these info with the history command?

The Sample Output would be:

Sat 04 Nov 2017 06:20:20 AM +03 111.111.111.111 : pwd Sat 04 Nov 2017 06:20:20 AM +03 111.123.123.111 : mkdir test Sat 04 Nov 2017 06:20:20 AM +03 123.123.44.32 : pwd

Help me to setup these changes via either .bash_profile or .bashrc

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • On a CentOS server(Forget to mention) – Muhammed Fasal Nov 04 '17 at 03:41
  • 2
    Please show your efforts. You can see this post to get started: https://stackoverflow.com/questions/11987761/how-to-find-date-wise-history-of-linux-commands-being-fired – codeforester Nov 04 '17 at 03:43
  • Thanks for your reply, I already enter this entry on .bash_profile and it shows date, time correctly. But unable to fetch out the IP address of users who execute those commands. entered below code in .bash_profile export HISTTIMEFORMAT="%c : " Output is : Sat 04 Nov 2017 06:24:35 AM +03 : history I need output as : – Muhammed Fasal Nov 04 '17 at 03:49
  • Sat 04 Nov 2017 06:20:20 AM +03 123.123.44.32 : pwd – Muhammed Fasal Nov 04 '17 at 03:49

1 Answers1

1

Though you can turn timestamps on in Bash history by setting HISTTIMEFORMAT, you cannot prefix a string to every line of the history file. You could use the DEBUG trap to achieve your goal, by maintaining your own history file:

save_history() {
  # make sure IP is set in .bash_profile instead of capturing it each time here
  printf '%s : %s : %s\n' "$(date)" "$IP" "$BASH_COMMAND" >> /path/to/history_file
}

trap save_history DEBUG

This way, the save_history function gets called before each command and it records the history in the file.


See also:

codeforester
  • 39,467
  • 16
  • 112
  • 140
  • Hi @codeforester Thanks for your answer, but I didn't quite understand well. Please provide the exact steps to accomplish this output to find out IP, date with history command. Once again thanks. :) – Muhammed Fasal Nov 04 '17 at 05:01
  • Use a combination of `ss` and `grep` to extract the IP. And understand that SO is not a free code writing service. You need to put your effort. – codeforester Nov 04 '17 at 06:04