1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[改良]SSHログイン監視(ログインがあったら通知/自IPは通知除外)

Last updated at Posted at 2021-02-24

/etc/ssh/sshrcというファイルを作成します。
このファイルはすべてのユーザがSSHログインした際に自動的に実行されます。

このファイル内でmailxコマンド(存在しない場合は yum install mailx)を使って、メール送信します。

全てのSSHログインを通知する

/etc/ssh/sshrc
MAIL_TO=to@example.com
echo ""$USER" has logged in from [$SSH_CLIENT] at `date +"%Y/%m/%d %H:%M:%S"` " | mail -s "[$HOSTNAME ]sshd login alert" $MAIL_TO

認知しているIPアドレスは通知しない

IPS変数に指定します。(複数指定したい場合は空白で区切ります)

/etc/ssh/sshrc
MAIL_TO=to@example.com

FOUND=0
IPS="123.456.78.901"
DETECT_IP=
for ip in $IPS
do
  if [ "${SSH_CLIENT:0:${#ip}}" = "$ip" ]; then
    FOUND=1
    DETECT_IP=$ip
  fi
done

if [ $FOUND = 0 ]; then
  echo ""$USER" has logged in from [$SSH_CLIENT] at `date +"%Y/%m/%d %H:%M:%S"` " | mail -s "[$HOSTNAME ]sshd login alert" $MAIL_TO
# else
#  echo "detect defined ip [$DETECT_IP]" | mail -s "[$HOSTNAME ]sshd login alert" $MAIL_TO
fi

$SSH_CLIENT$HOSTNAMEは環境変数です。

付録/届くメール

上記コードだと以下の様なメールが届きます。

Image from Gyazo

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?