Files
dock/实时 history 监控

74 lines
2.3 KiB
Plaintext

# 创建最简单的监控系统
cat > /usr/local/bin/mt << 'EOF'
#!/bin/bash
LOG="/root/command_logs/monitor.log"
PID="/tmp/monitor.pid"
case "$1" in
start)
echo 'export PROMPT_COMMAND="history -a; history -c; history -r"' >> ~/.bashrc
source ~/.bashrc
(
mkdir -p /root/command_logs
declare -A size
for u in /home/* /root; do
[ -d "$u" ] && h="$u/.bash_history" && [ -f "$h" ] && size["$(basename "$u")"]=$(stat -c%s "$h" 2>/dev/null || echo 0)
done
while true; do
for u in /home/* /root; do
[ -d "$u" ] || continue
user=$(basename "$u")
hfile="$u/.bash_history"
[ -f "$hfile" ] || continue
cur=$(stat -c%s "$hfile" 2>/dev/null || echo 0)
last=${size["$user"]:-0}
if [ "$cur" -gt "$last" ]; then
cmd=$(tail -n 1 "$hfile" 2>/dev/null)
if [ -n "$cmd" ] && [ ${#cmd} -gt 1 ]; then
case "$cmd" in
ls|cd|pwd|ll|history|exit|clear|mt|".") continue ;;
*)
ip="unknown"
[ -n "$SSH_CLIENT" ] && ip=$(echo "$SSH_CLIENT" | awk '{print $1}')
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $user: $cmd (from: $ip)" >> "$LOG"
;;
esac
fi
size["$user"]=$cur
fi
done
sleep 2
done
) &
echo $! > "$PID"
echo "监控已启动"
;;
stop)
[ -f "$PID" ] && kill $(cat "$PID") 2>/dev/null
rm -f "$PID"
echo "监控已停止"
;;
view)
[ -f "$LOG" ] && tail -f "$LOG" || echo "无日志"
;;
*)
echo "用法: mt [start|stop|view]"
;;
esac
EOF
chmod +x /usr/local/bin/mt
# 设置开机启动
(crontab -l 2>/dev/null; echo "@reboot /usr/local/bin/mt start >/dev/null 2>&1") | crontab -
# 启动
mt start
echo "安装完成! 使用 'mt view' 查看日志"