Differentiate between exit and session timeout

試著忘記壹切 提交于 2019-12-01 22:03:23

问题


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:

  1. the timeout is triggering EXIT, which I do not want
  2. I do not know how to trap the timeout specifically

How can I solve these open issues?


回答1:


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:

  • Capture command prompt time - start)
  • At 'exit' event, check if (now-start) > TMOUT
  • Normally, exit, CTRL/D, etc will finish in 1-2 seconds.
#! /bin/bash
function pre_cmd {
        START=$SECONDS
}

function log_exit {
    if [ "$((SECONDS-START-TMOUT))" -ge 0 ] ; then
       echo "TIMEOUT"
    else
       echo "Normal Exit"
    fi
}

TMOUT=15
PROMPT_COMMAND=pre_cmd
trap 'log_exit' EXIT



回答2:


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.

function my_trap {
  local X=$1
  if [ "$X" = "$(kill -l ALRM)" ] ; then
     Log Timeout
  else
     Log Exit/EOF
  fi
}

trap 'my_trap $?' EXIT


来源:https://stackoverflow.com/questions/58502915/differentiate-between-exit-and-session-timeout

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!