Files
dock/实时 history 监控

83 lines
2.6 KiB
Plaintext

# 创建极简监控系统
cat > /tmp/simple_monitor.sh << 'EOF'
#!/bin/bash
LOG_FILE="/tmp/command_monitor.log"
PID_FILE="/tmp/monitor_simple.pid"
case "$1" in
start)
echo "启动极简监控..."
# 设置实时history
echo 'export PROMPT_COMMAND="history -a; history -c; history -r"' >> ~/.bashrc
source ~/.bashrc
# 启动监控进程
(
echo "=== 监控启动: $(date) ===" > "$LOG_FILE"
declare -A sizes
while true; do
for user_dir in /home/* /root; do
[ -d "$user_dir" ] || continue
user=$(basename "$user_dir")
history_file="$user_dir/.bash_history"
[ -f "$history_file" ] || continue
current=$(stat -c%s "$history_file" 2>/dev/null || echo 0)
last=${sizes["$user"]:-0}
if [ "$current" -gt "$last" ]; then
cmd=$(tail -n 1 "$history_file" 2>/dev/null)
if [ -n "$cmd" ] && [ ${#cmd} -gt 1 ]; then
case "$cmd" in
ls|cd|pwd|ll|history|exit|clear|".") 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_FILE"
;;
esac
fi
sizes["$user"]=$current
fi
done
sleep 2
done
) &
echo $! > "$PID_FILE"
echo "监控已启动 (PID: $!)"
echo "查看日志: tail -f $LOG_FILE"
;;
view)
if [ -f "$LOG_FILE" ]; then
tail -f "$LOG_FILE"
else
echo "暂无日志,请先启动监控: $0 start"
fi
;;
stop)
if [ -f "$PID_FILE" ]; then
kill $(cat "$PID_FILE") 2>/dev/null
rm -f "$PID_FILE"
echo "监控已停止"
else
echo "监控未运行"
fi
;;
*)
echo "使用方法: $0 {start|view|stop}"
;;
esac
EOF
chmod +x /tmp/simple_monitor.sh
# 启动极简监控
/tmp/simple_monitor.sh start
# 测试
echo "test_simple_$(date +%s)" >> ~/.bash_history
sleep 2
tail -5 /tmp/command_monitor.log