Is there a way to configure sshd so that it sends me an e-mail whenever someone logs in via SSH?
-
Any particular reason you want this instead of, say, a webpage displaying current status or a summary at the end of the day? – Alex Holst Jan 27 '11 at 16:56
3 Answers
Sshd itself won't do this for you, but you could probably accomplish what you want using the pam_exec
module (assuming that you've got SSH using PAM
). Something like this might work (in /etc/pam.d/sshd
):
session optional pam_exec.so /path/to/your/script
You could also watch /var/log/secure
(or your local equivalent) for messages sshd logs when someone logs in, and trigger and email based on that.
You could also probably hack something together using the ForceCommand
option in sshd. You would have ForceCommand
run a script that would send the email and then use the SSH_ORIGINAL_COMMAND
environment variable to run the user's shell (or whatever other command they were attempting to run). I only mention this because it might work, not because I think it's a good idea.

- 43,623
- 14
- 121
- 180
-
1+1 for pam_exec, the nicest way to introduce session "jobs" that aren't really part of the user's shell. – Flexo Jan 27 '11 at 15:51
You could append this to the end of /etc/profile
/bin/bash -c 'HN=`/bin/hostname`; IP=`/bin/hostname -i`; /bin/bash -c "/bin/hostname -i; /bin/hostname; echo; /usr/bin/who --ips; echo; /usr/bin/who --all" | /usr/bin/mailx -s "LOGIN ALERT - $HN ($IP)" root'
This will email root with a list of logged in users everytime bash (the user's shell) is started.

- 375
- 2
- 3
-
1That's unnecessarily long and complex and includes redundant commands. Also, there's no reason I can think of that you'd need to use `bash -c` (twice no less!) since `/etc/profile` is already being executed by the shell and there's nothing Bash-specific in what you posted (it might have to be changed if the user's shell is csh or something). If you need to group commands to be piped into `mail` just do `{ cmd; cmd; cmd; } | mail`. – Dennis Williamson Jan 27 '11 at 16:10
-
1There are some automatically set variables you could make use of without calling `hostname` (four times!). And `hostname -i` gives me "127.0.0.1" which isn't very useful. In any case, it should be made conditional so local logins aren't included in order to fit what the OP probably wants. – Dennis Williamson Jan 27 '11 at 16:11
-
Although your specific example is horrible, this is generally the best solution. However, never modify /etc/profile. Just create your own script in /etc/profile.d/. – Cerin Mar 22 '12 at 21:43
You could use swatch (which is designed to watch logfiles and send emails with lines matching regexps) to monitor /var/log/secure
(or wherever your OS logs ssh logins), looking for lines like
sshd[xxxxx]: pam_unix(sshd:session): session opened for user foo by (uid=0)
and sending mails accordingly.

- 79,770
- 20
- 184
- 232