I have the following requierements:
- produce audit log when bash session has been terminated by the user (exit)
- produce audit log when bash session has timed out
Those audit logs must be different. I am playing around with the following script trap.sh
:
export TMOUT=10
function handle-timeout {
echo "Timeout"
}
function handle-exit {
echo "Exit"
}
trap handle-exit EXIT
Now if I do:
valegon@precision ~ (master) $ bash
valegon@precision ~ (master) $ source trap.sh
valegon@precision ~ (master) $ exit
Exit
It works as expected. If instead, I wait for the timeout to happen:
valegon@precision ~ (master) $ bash
valegon@precision ~ (master) $ source trap.sh
valegon@precision ~ (master) $ timed out waiting for input: auto-logout
Exit
There are two problems here:
- the timeout is triggering EXIT, which I do not want
- I do not know how to trap the timeout specifically
How can I solve these open issues?
Same as Distinguish between user logout and session expired logout (SSH and web console)
I'm posting the same answer that I've posted there.
...
For normal sessions, which will have a login event, you can set a trap on the 'EXIT' event. This will cover explicit logout (CTRL/D, or exit), gettng killed by signal (NOT signal 9), and timeout. Look for bash 'trap' command. Those can be set at the loginn startup script (bashrc)
EDIT
It's possible to get indication of 'TIMEOUT' by checking '$?' in the TRAP handler. It will be 142 corresponding to ALRM signal (kill -l 142=ARLM). This is not explicitly document, but is consistent with the default signal handler for kill -ALRM.
2nd Attempt
Based on feedback, previous solution using trap on EXIT does not work well. Alternative, based on using PROMPT_COMMAND seems to give better mileage.
Basic Logic: