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,418

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,418