几周前,我认为编写一个脚本以便在用户登录我的服务器时向我发送电子邮件是个好主意。
因此,我提供了一个完美运行的脚本notifyLogin.sh
,然后我决定从每个用户的脚本中调用它 .bash_login
。
ssh
-t
但我发现有人可以使用switch 来选择可用的 shell 来登录我的服务器。例如:
ssh user@myserver -t sh
这样,.bash_login
不执行,也不执行/etc/profile
。
有什么方法可以notifyLogin.sh
在登录时独立于 shell 类型进行调用吗? (它应该总是有效)
答案1
不要重新发明轮子,让rsyslog
一切为您做。当系统日志消息中的模式在到达文件之前匹配时,它能够发送电子邮件。
在下面设置您的电子邮件地址和 SMTP 服务器并将其放入您的/etc/rsyslog.conf
或将其放入/etc/rsyslog.d/
并重新启动rsyslog
$ModLoad ommail
$ActionMailSMTPServer localhost
$ActionMailFrom [email protected]
$ActionMailTo [email protected]
$template mailSubject,"Login Alert on %hostname%"
$template mailBody,"\n\n%msg%"
$ActionMailSubject mailSubject
$ActionExecOnlyOnceEveryInterval 1
# the if ... then ... mailBody mus be on one line!
if $msg contains 'session opened for user' then :ommail:;mailBody
当与消息中的 rsyslog
字符串匹配时,这将触发电子邮件。session opened for user
您可以查看/var/log/auth.log
来自的消息,sshd
看看还有什么可以用作模式。
来源:rsyslog 邮件
答案2
首先,您不应依赖用户的 .profile,因为他们可以更改它。如果真的是的话你的服务器,您可以:
- 定期测试 auth.log、utmp 等中的条目(或由 inotify 触发)
- 为 编写一个包装器
/bin/login
,它可以完成您的工作,然后执行真正的/bin/login
. (我不太确定例如 ssh 是否执行/bin/login
,但我希望如此。)但我不能推荐这样做 - 这太危险了。
答案3
/var/log/auth.log
跟踪对您系统的尝试
cat /var/log/auth.log grep sshd.\*Failed
这可以 grep 失败的尝试,时间戳也可用,因此您可以将其调整到您的脚本,也可以使用
tail -f /var/log/auth.log
您可以一直跟踪输入,然后执行一些正则表达式。
答案4
遵循@Creek 的回答;使用 rsyslog,匹配多个用户(不是最好的实现,可能可以用正则表达式替换,但它可以工作)
$ModLoad ommail
$ActionMailSMTPServer localhost
$ActionMailFrom [email protected]
$ActionMailTo [email protected]
$template mailSubject,"Login alert on %hostname%"
# mailBody must be on one line!
$template mailBody,"\n\n%msg%"
$ActionMailSubject mailSubject
$ActionExecOnlyOnceEveryInterval 1
if $msg contains 'session opened for' then {
if $msg contains 'USER1' then :ommail:;mailBody
# Repetition required (did not investigate why)
$ActionMailSMTPServer localhost
$ActionMailFrom [email protected]
$ActionMailTo [email protected]
$template mailSubject,"Login alert on %hostname%"
$template mailBody,"\n\n%msg%"
$ActionMailSubject mailSubject
$ActionExecOnlyOnceEveryInterval 1
if $msg contains 'USER2' then :ommail:;mailBody
}