概要
ssh したら slack に通知します
s6-overlay という機能を使います
環境
- macOS 15.7.1
- docker 29.1.2
- linuxserver/openssh-server 10.0_p1-r10-ls211
compose.yaml
services:
ssh_server:
image: ghcr.io/linuxserver/openssh-server
container_name: ssh_server
ports:
- "2222:2222"
- "10022:10022"
environment:
- PUID=1000
- PGID=1000
- PASSWORD_ACCESS=false
- USER_NAME=operator
- PUBLIC_KEY_FILE=/config/ssh/authorized_keys
volumes:
- ./custom-cont-init.d:/custom-cont-init.d:ro
- ./custom-services.d:/custom-services.d:ro
- ./config/ssh:/config/ssh
restart: unless-stopped
custom-services.d/run
#!/usr/bin/execlineb -P
with-contenv
exec bash /custom-services.d/notify_ssh/notify.sh
- chmod +x custom-services.d/run
custom-services.d/notify_ssh/notify.sh
#!/usr/bin/env bash
LOGFILE="/config/logs/openssh/current"
WEBHOOK_URL="https://hooks.slack.com/services/xxx/xxx/xxx"
# ログファイル生成待ち
while [ ! -f "$LOGFILE" ]; do
sleep 1
done
echo "[notify-ssh] starting log monitor"
# ログ監視
tail -Fn0 "$LOGFILE" | while read -r line; do
# ① 接続ログ (Connection from)
if echo "$line" | grep -q "Connection from"; then
IP=$(echo "$line" | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}")
curl -s -X POST -H 'Content-Type: application/json' \
--data "{\"text\": \"👀 SSH access from $IP\"}" \
"$WEBHOOK_URL" >/dev/null
fi
# ② 成功ログ (Accepted)
if echo "$line" | grep -q "Accepted"; then
IP=$(echo "$line" | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}")
USER=$(echo "$line" | awk '{print $(NF-5)}')
curl -s -X POST -H 'Content-Type: application/json' \
--data "{\"text\": \"🔐 SSH login success: user=$USER, ip=$IP\"}" \
"$WEBHOOK_URL" >/dev/null
fi
# ③ 失敗ログ (Failed)
if echo "$line" | grep -q "Failed"; then
IP=$(echo "$line" | grep -oE "([0-9]{1,3}\.){3}[0-9]{1,3}")
curl -s -X POST -H 'Content-Type: application/json' \
--data "{\"text\": \"⚠️ SSH failed login attempt from $IP\"}" \
"$WEBHOOK_URL" >/dev/null
fi
done
- chmod +x custom-services.d/notify_ssh/notify.sh
最後に
コンテナはこの方法がいいです
systemd があれば socat なども使えます
0 件のコメント:
コメントを投稿