1

When commands are saved to history in Linux, is there some way to prepend the command line in the history with the remote SSH IP address and process ID so that it's easy to group commands from the same SSH session and also see where they were run from? I know how to get the IP address and process ID, but I don't know how to get it to save that to the history.

Is there some way to modify the command line that gets saved to .bash_history or some other way to accomplish this?

sa289
  • 1,308
  • 2
  • 17
  • 42
  • 1
    Don't allow anyone to share accounts, nor use the root account for routine administration. – Michael Hampton Jul 31 '14 at 21:09
  • One of the cases I'm interested in is even if it's just a single user (regardless of root or not), if having multiple shells open at once this would permit being able to see what commands were run, and being able to distinguish which shell they were run in. Separately, in some real world cases such as shared hosting on some hosts, only a single SSH account may be available and must be shared by multiple users. – sa289 Jul 31 '14 at 21:48
  • 1
    Using the bash history is probably not really going to give you want you want. You might instead need to look at setting up auditd or something to monitor processes. – Zoredache Jul 31 '14 at 22:09
  • Good to know - that looks useful. Here's a post going into more detail on that in case it's helpful to anyone coming across this post http://serverfault.com/questions/470755/log-all-commands-run-by-admins-on-production-servers – sa289 Jul 31 '14 at 22:27

1 Answers1

0

Even if it was possible to modify the command that gets saved it wouldn't be desirable to do so because that would affect the actual command history if you go to use it (such as via up arrow, ctrl+r, etc). Comments are safely permitted in the history file (such as the timestamp), and so based on that, here's a way to be able to log this information to the history as comments. It has the drawback that pressing ctrl+c will cause $PROMPT_COMMAND to run and thus unnecessary comments be added to the history file, but that is relatively minor and other than that it seems to do the trick. The following can be added to the target user's ~/.bash_profile file. The comment that gets added is verbose for the sake of clarity.

shopt -s histappend
PROMPT_COMMAND='history -a; ssh_ip=`echo $SSH_CLIENT|awk "{print \\\$1}"`; echo "#command above was run from PPID $PPID, IP $ssh_ip" >>~/.bash_history '
sa289
  • 1,308
  • 2
  • 17
  • 42