File: notifier.py

package info (click to toggle)
sshproxy 0.6.0~beta2-2
  • links: PTS, VCS
  • area: main
  • in suites: lenny
  • size: 956 kB
  • ctags: 1,296
  • sloc: python: 8,932; sh: 268; sql: 40; makefile: 38; xml: 21
file content (239 lines) | stat: -rw-r--r-- 7,255 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2007 Michal Mazurek; WALLIX, SARL. <michal.mazurek at wallix dot com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301  USA

import smtplib
import types
import socket, os
from sshproxy.config import get_config, ConfigSection
from sshproxy.util import istrue
from sshproxy import log

message_template = """
Reported error: %(reason)s
Client: %(client)s
Site: %(site)s
Connection Type: %(conntype)s
Date: %(when)s
Additional message:
%(msg)s

--
Your sshproxy <%(sshproxy_id)s>
"""


class EmailNotifierConfigSection(ConfigSection):
    section_id = 'email_notifier'
    section_defaults = {
        'admin_email': '',
        'smtp_server': 'localhost',
        'smtp_port': '25',
        'smtp_login': '',
        'smtp_password': '',
        'smtp_sender': '%s@%s' % (os.environ['USER'], socket.getfqdn()),
        'smtp_tls': 'no',
        'message_template': message_template.replace('%', '%%'),
        }
    types = {
        'smtp_port': int,
        }

EmailNotifierConfigSection.register()



class Email(object):
    """Class for sending emails using smtplib"""
    
    recipients = []
    
    def __init__(self, server, port=25, login="", password="", tls=False):
        """Constructor
        
        Email(server, [port, [login, [password]], tls])
        
        @param server: smtp server address
        @param port: smtp port number
        @param login: auth username (optional)
        @param password: auth password (optional)
        @param tls: use TLS (defaults to False)
        """
        self.smtp_server = server
        self.smtp_port = port
        self.smtp_tls = tls
        self.login = login
        self.password = password

    def new(self, recipients=None, sender=None, subject=None, msg=None):
        """Creating new email
        
        @param recipient: string or iterable object containing string
        @param sender: string with sender address
        @param subject: subject of message
        @param msg: message body
        """
        try:
            if types.StringType == type(recipients):
                recipients = [recipients]
                
            for recipient in recipients:
                self.recipients.append(recipient)
        except TypeError:
            raise TypError, "'recipients' is not iterable, nor a string"
        
        self.sender = sender
        self.subject = subject
        self.msg = msg
        
    def _connect_to_smtp(self):
        """Connecting to smtp server, this methods runs also self._authorize()"""
        self._connection = smtplib.SMTP(self.smtp_server, self.smtp_port)
        self._starttls()
        self._authorize()
        
        
    def _starttls(self):
        """If TLS is requested, try to put the connection in TLS mode."""
        if self.smtp_tls:
            self._connection.starttls()

    def _authorize(self):
        """If there are give login and password, it tries to authorize on
        smtp server"""
        if self.login and self.password:
            self._connection.login(self.login, self.password)

    def send_email(self):
        """Method which sends email, if there are any problems it raises
        smtplib.SMTPException"""
        
        msg = ""
        msg += "From: %s\n" % self.sender
        msg += "To: %s\n" % ", ".join(self.recipients)
        msg += "Subject: %s\n\n%s" % (self.subject, self.msg)
        try:
            self._connect_to_smtp()
        except (socket.error, socket.herror):
            return False
        result = self._connection.sendmail(self.sender, self.recipients, msg)
        if result:
            errmsg = ""
            for recp in result.keys():
                errmsg += """Server returned error for recipient: %s
                
                %s
                %s
                """ % (recp, result[recp][0], result[recp][1])
            
            raise smtplib.SMTPException, errmsg
        
        self._connection.quit()
        
        return True
        

from sshproxy.registry import get_class

Server = get_class("Server")

class EmailNotifierServer(Server):

    def do_work(self):
        self.get_site_name()
        Server.do_work(self)
    
    def get_site_name(self):
        """getting the site name"""
        if len(self.args) == 0:
            self.g_site = "Console Session"
            self.g_conn_type = "scp"
        else:
            if self.args[0] == "scp":
                self.g_conn_type = "scp"
                argv = self.args[1:]
                while True:
                    if argv[0][0] == '-':
                        argv.pop(0)
                        continue
                    break
                
                self.g_site = argv[0].split(":", 1)[0]
            elif self.args[0][0] != '-':
                
                if len(self.args) > 1:
                    self.g_conn_type = "remote_exec"
                else:
                    self.g_conn_type = "shell"
                self.g_site = self.args[0]
            else:
                self.g_site = "proxy_command"
        return self.g_site
    
    def report_failure(self, reason, *args, **kwargs):
        """Reporting error
        
        @param reason: reason of failure"""
        from datetime import datetime

        cfg = get_config('email_notifier')

        tpldict = {}
        
        tpldict['reason'] = reason
        if len(args) > 0:
            tpldict['msg'] = args[0]
        else:
            tpldict['msg'] = "No additional message."
        
        
        tpldict['client'] = self.username
        tpldict['site'] = self.g_site
        tpldict['when'] = datetime.now()
        tpldict['conntype'] = self.g_conn_type
        tpldict['sshproxy_id'] = cfg['smtp_sender'] # ?


        server = cfg['smtp_server']
        try:
            port = cfg['smtp_port']
        except ValueError:
            port = 25
            
        login = cfg['smtp_login']
        password = cfg['smtp_password']
        
        admin_email = cfg['admin_email']
        sender = cfg['smtp_sender']

        tls = istrue(cfg["smtp_tls"])
        
        msg = cfg['message_template'] % tpldict

        if admin_email != "" and "@" in admin_email:
            email = Email(server, port, login, password, tls=tls)
            
            email.new(admin_email, sender, "Failure Report", msg)
            
            try:
                email.send_email()
            except smtplib.SMTPException, e:
                log.exception(e)
        Server.report_failure(self, reason, *args, **kwargs)