出于安全考虑,在用户通过ssh登录服务器的时候向管理员自动发送一封邮件,通知登录用户的用户名和ip。这是一个不错的安全防范机制。

方法一、建立/etc/ssh/sshrc文件,内容如下:

#!/bin/bash
/usr/sbin/sendmail -t >/dev/null 2>&1 <<EOF
From: xupeng <peng.x.men@gmail.com>
To: xupeng.js@gmail.com
Subject:$USER@`hostname` login from ${SSH_CLIENT%%}  

`date` http://www.123cha.com/ip/?q=${SSH_CLIENT%% *}
EOF

if read proto cookie && [ -n "$DISPLAY" ]; then
        if [ `echo $DISPLAY | cut -c1-10` = 'localhost:' ]; then
                # X11UseLocalhost=yes  
                echo add unix:`echo $DISPLAY | cut -c11-` $proto $cookie  
        else
                # X11UseLocalhost=no  
                echo add $DISPLAY $proto $cookie  
        fi | xauth -q -
fi


也可以只跟踪某个用户的登陆,比如root(当然,最好禁止root用ssh登陆),那就建立/root/.ssh/rc内容同上。


方法二、在/etc/profile里增加如下:

echo 'ALERT - Root Shell Access (Server Name) on:' `date` `who` | mail -s "Alert: Root Access from `who | cut -d "(" -f2 | cut -d ")" -f1`" 644100988@qq.com

方法三、使用python smtp认证发送:

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import smtplib
from email.mime.text import MIMEText

#要发给谁
mailto_list=["644100988@qq.com"]
#设置服务器,用户名、口令以及邮箱的后缀
mail_host="smtp.163.com"
mail_user="xxx"
mail_pass="xxx"
mail_postfix="163.com"

def send_mail(to_list,sub,content):
    '''
    to_list:发给谁
    sub:主题
    content:内容
    send_mail("aaa@126.com","sub","content")
    '''
    me=mail_user+"<"+mail_user+"@"+mail_postfix+">"
    msg = MIMEText(content)
    msg['Subject'] = sub
    msg['From'] = me
    msg['To'] = ";".join(to_list)
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.login(mail_user,mail_pass)
        s.sendmail(me, to_list, msg.as_string())
        s.close()
        return True
    except Exception, e:
        print str(e)
        return False

ip = os.popen("echo ${SSH_CLIENT%% *}").read().rstrip()
localip = os.popen("/sbin/ifconfig -a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d \"addr:\"|sed -n \"1p\"").read().rstrip();
user = os.popen("echo $USER").read()
hostname = os.popen("echo `hostname`").read()
time = os.popen("echo `date`").read()
ip = 'http://www.123cha.com/ip/?q='+ip
title = hostname.rstrip()+'('+localip+')'+'主机的登录信息'
message = '登录时间:'+time + '登录用户:'+user + '登录主机:'+hostname + '登录来源:'+ip
send_mail(mailto_list,title,message);
将以上脚本保存为login.py

新增/etc/ssh/sshrc

#!/bin/bash

/usr/bin/python /root/login.py
python脚本需要2.6.x以上环境运行