我想创建一个包含某些事件日志的日志文件,例如:
- 登录 gnome
- 日志屏幕
- 解锁屏幕
- 登出
我的计划是编写一个脚本,作为 gnome 会话的子进程在后台运行。它将首先附加“LOGIN”,监视屏幕锁定/解锁,并在收到 SIGHUP(表示会话结束)时附加“LOGOUT”。
我编写了一个脚本 [1],如果我在 shell 中启动它就可以工作,但它很笨重。我希望这个程序在后台运行——我不想每次登录时都记得启动它。
有人可以指出我正确的方向吗?
[1] 脚本:
#!/bin/bash
# param $1: type, in:
# ["SCREEN_LOCKED",
# "SCREEN_UNLOCKED",
# "LOGIN",
# "LOGOUT",
# "SIGINT",
# "SIGTERM"]
function write_log {
if [ -z $1 ]; then
1="unspecified"
fi
echo -e "$1\t$(date)" >> "$LOG"
}
function notify {
echo "$@" >&2
}
function show_usage {
notify "Usage: $0 login <address> <logfile>"
notify "Parameters:"
notify " login: You must use the string 'login' to avoid seeing this message."
notify " <logfile>: File to store logs."
notify ""
notify "This script is designed to go in the bashrc file, and be called in the"
notify "form of: $0 login '$USER@$(uname -n)' >>/path/to/logfile &"
notify ""
}
if [ "$#" -eq 0 ]; then
show_usage
exit 1
fi
if [ "$1" != "login" ]; then
show_usage
notify "Error: first parameter must be the string 'login'."
exit 1
fi
LOG="$2"
if [ -z "$LOG" ]; then
notify "Error: please specify a logfile."
exit 1
elif [ -f "$LOG" ]; then
# If the logfile exists, verify that the last action was a LOGOUT.
LASTACTION=$(tail -1 "$LOG" | awk '{print $1}')
if [ $LASTACTION != "LOGOUT" ]; then
notify "Logfile '$LOG' exists but last action was not logout: $LASTACTION"
exit 1
fi
else
# If the file does not exist, create it.
touch "$LOG" || ( notify "Cannot create logfile: '$2'" && exit 1 )
fi
# Begin by logging in:
write_log "LOGIN"
# Handle signals by logging:
trap "write_log 'LOGOUT'; exit" SIGHUP
trap "write_log 'INTERRUPTED_SIGINT'; exit 1" SIGINT
trap "write_log 'INTERRUPTED_SIGTERM'; exit 1" SIGTERM
# Monitor gnome for screen locking. Log these events.
dbus-monitor --session "type='signal',interface='org.gnome.ScreenSaver'" | \
(
while true; do
read X;
if echo $X | grep "boolean true" &> /dev/null; then
write_log "SCREEN_LOCKED"
elif echo $X | grep "boolean false" &> /dev/null; then
write_log "SCREEN_UNLOCKED"
fi
done
)