root / pykota / trunk / bin / pkmail @ 1952

Revision 1952, 6.2 kB (checked in by jalet, 19 years ago)

Introduced the new pkmail command as a simple email gateway

  • Property svn:eol-style set to native
  • Property svn:executable set to *
  • Property svn:keywords set to Author Date Id Revision
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# An email gateway for PyKota
5#
6# PyKota - Print Quotas for CUPS and LPRng
7#
8# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23# $Id$
24#
25# $Log$
26# Revision 1.1  2004/11/21 21:50:03  jalet
27# Introduced the new pkmail command as a simple email gateway
28#
29
30import sys
31import os
32import popen2
33import smtplib
34import email
35
36from pykota.tool import PyKotaTool, PyKotaToolError, crashed, N_
37from pykota.pdlanalyzer import PDLAnalyzer, PDLAnalyzerError
38
39__doc__ = N_("""pkmail v%s (c) 2003-2004 C@LL - Conseil Internet & Logiciels Libres
40
41Email gateway for PyKota.
42
43command line usage :
44
45  pkmail  [options]
46
47options :
48
49  -v | --version       Prints pkmail's version number then exits.
50  -h | --help          Prints this message then exits.
51 
52   
53  This command is meant to be used from your mail server's aliases file,
54  as a pipe. It will then accept commands send to it in email messages,
55  and will send the answer to the command's originator.
56 
57  To use this command, create an email alias in /etc/aliases with
58  the following format :
59 
60    pykotacmd: "|/usr/bin/pkmail"
61   
62  Then run the 'newaliases' command to regenerate the aliases database.
63 
64  You can now send commands by email to 'pykotacmd@yourdomain.com', with
65  the command in the subject.
66 
67  List of supported commands :
68 
69        report [username]
70 
71  NB : For pkmail to work correctly, you may have to put the 'mail'
72  system user in the 'lpadmin' system group to ensure this user can
73  read the /etc/pykota/pykotadmin.conf file, and restart your
74  mail server (e.g. /etc/init.d/exim restart). It is strongly advised
75  that you think at least twice before doing this though.
76 
77  Use at your own risk !
78 
79This program is free software; you can redistribute it and/or modify
80it under the terms of the GNU General Public License as published by
81the Free Software Foundation; either version 2 of the License, or
82(at your option) any later version.
83
84This program is distributed in the hope that it will be useful,
85but WITHOUT ANY WARRANTY; without even the implied warranty of
86MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
87GNU General Public License for more details.
88
89You should have received a copy of the GNU General Public License
90along with this program; if not, write to the Free Software
91Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
92
93Please e-mail bugs to: %s""")
94       
95       
96class PKMail(PyKotaTool) :       
97    """A class for pkmail."""
98    def main(self, files, options) :
99        """Accepts commands passed in an email message."""
100        data = sys.stdin.read()
101        message = email.message_from_string(data)
102        useremail = message["From"]
103        whoami = message["To"]
104        cmdargs = message["Subject"].split()
105        try :
106            (command, arguments) = (cmdargs[0].capitalize(), cmdargs[1:])
107        except IndexError :   
108            raise PyKotaToolError, "No command found !"
109       
110        self.logdebug("Launching internal command '%s' with arguments %s" % (command, arguments))
111        cmdfunc = getattr(self, "cmd%s" % command, self.cmdDefault)
112        result = cmdfunc(arguments)
113       
114        self.logdebug("Sending answer to : %s" % useremail)
115        server = smtplib.SMTP(self.smtpserver)
116        server.sendmail(whoami, [ useremail ], "From: %s\nTo: %s\nSubject: Result of your commands\n\n%s\n" % (whoami, useremail, result))
117        server.quit()
118        self.logdebug("Answer sent to : %s" % useremail)
119       
120        return 0
121       
122    def runCommand(self, cmd) :   
123        """Executes a command."""
124        self.logdebug("Launching : '%s'" % cmd)
125        os.environ["PATH"] = "%s:/bin:/usr/bin:/usr/local/bin:/opt/bin:/sbin:/usr/sbin" % os.environ.get("PATH", "")
126        child = popen2.Popen3(cmd)
127        child.tochild.close()
128        result = child.fromchild.read()
129        status = child.wait()
130        if os.WIFEXITED(status) :
131            status = os.WEXITSTATUS(status)
132        self.logdebug("'%s' exited with status %s" % (cmd, status))
133        return result
134       
135    def cmdDefault(self, arguments) :   
136        """Default command : sends an 'unknown command' message."""
137        return "Unknown command."
138       
139    def cmdReport(self, args) :   
140        """Generates a print quota report."""
141        return self.runCommand("repykota %s" % ' '.join([ '"%s"' % a for a in args ]))
142           
143if __name__ == "__main__" : 
144    retcode = 0
145    try :
146        defaults = { \
147                   }
148        short_options = "vh"
149        long_options = ["help", "version"]
150       
151        # Initializes the command line tool
152        mailparser = PKMail(doc=__doc__)
153       
154        # parse and checks the command line
155        (options, args) = mailparser.parseCommandline(sys.argv[1:], short_options, long_options, allownothing=1)
156       
157        # sets long options
158        options["help"] = options["h"] or options["help"]
159        options["version"] = options["v"] or options["version"]
160       
161        if options["help"] :
162            mailparser.display_usage_and_quit()
163        elif options["version"] :
164            mailparser.display_version_and_quit()
165        else :
166            retcode = mailparser.main(args, options)
167    except SystemExit :       
168        pass
169    except :
170        try :
171            mailparser.crashed("pkmail failed")
172        except :   
173            crashed("pkmail failed")
174        retcode = -1
175
176    try :
177        mailparser.storage.close()
178    except (TypeError, NameError, AttributeError) :   
179        pass
180       
181    sys.exit(retcode)   
Note: See TracBrowser for help on using the browser.