bash 在 ssh 登录时发送电子邮件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7405406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:46:28  来源:igfitidea点击:

Send email on ssh login

bashemailssh

提问by Tech4Wilco

I want to make sure everytime someone is login into my server I receive an email saying:

我想确保每次有人登录我的服务器时,我都会收到一封电子邮件:

ALERT Shell Access on: Tue Jun 16 11:04:10 CDT 2009 user123 pts/0 2009-06-16 11:04

ALERT Shell 访问时间:Tue Jun 16 11:04:10 CDT 2009 user123 pts/0 2009-06-16 11:04

So I put this code:

所以我把这个代码:

echo 'ALERT Shell Access on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d"(" -f2 | cut -d")" -f1`" [email protected]

in the .bashrc.

.bashrc.

Why I don't receive any emails?

为什么我收不到任何邮件?

Thank you for your help, J

谢谢你的帮助,J

回答by Sorin

.bashrc is executed when bash is run as a interactive non-login shell, which is not the case when you ssh. Add the same code in .bash_profile which should be run when the shell is a login shell

.bashrc 在 bash 作为交互式非登录 shell 运行时执行,而 ssh 则不是这种情况。在 .bash_profile 中添加相同的代码,当 shell 是登录 shell 时应该运行

Note: Many distributions source .bashrc from .bash_profile, I may be wrong and the issue may not be about .bashrc / .bash_profile

注意:许多发行版从 .bash_profile 获取 .bashrc,我可能错了,问题可能与 .bashrc / .bash_profile 无关

回答by Pipo

Add into /etc/ssh/sshrc

添加到 /etc/ssh/sshrc

ip=`echo $SSH_CONNECTION | cut -d " " -f 1`

logger -t ssh-wrapper $USER login from $ip
msg="User $USER just logged in from $ip"
echo $msg|mail -s $msg root