• Facebook
  • Twitter
  • Reddit
  • StumbleUpon
  • Digg
  • email

# -*- coding: iso-8859-1 -*-
#
# Copyright 2003-2010 University of Oslo, Norway
#
# This file is part of Cerebrum.
#
# Cerebrum 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.
#
# Cerebrum 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 Cerebrum; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 
import os
import subprocess
import win32api
import pywintypes
import logging
import ADconstants
 
 
const = ADconstants.Constants()
 
from ADobject import ADObject
 
class Exchange(ADObject):
    """
    Class with methods for Exchange 2007 and newer. Uses poershell
    commands to manipulate exchange. IMPORTANT: Exchange Management
    Tools and powershell must be installed for this class to work.
    """
 
    def __init__(self, *args, **kwargs):
        super(Exchange, self).__init__(*args, **kwargs)
 
    def run_UpdateRecipient(self, sAMAccountname, DC=None):
        """
        Method to run powershell cmdlet Update-Recipient on Exchange
        server for a user. Since python is 32 bit a direct call for
        PowerShell will invoke the 32 bit version of powershell.
        Exchange 2007 and newer is 64 bit only and needs to be
        controlled with 64 bit powershell. Therefore copy the 64 bit
        version of the powershell executable to C:\\cerebrum\python\\
        and rename it \PowerShell_cerebrum.exe.
        """
        self.clearObject()
        msexshell_path1 = "C:\\Program Files\\Microsoft\\Exchange Server\\Bin\\exshell.psc1"
        ps_cmd = 'C:\\cerebrum\python\\PowerShell_cerebrum.exe'
        cmd = '%s -PSConsoleFile "%s" -Command "Update-Recipient -Identity "%s""' % (
            ps_cmd, msexshell_path1, sAMAccountname)
        if DC is not None:
            cmd += ' -DomainController %s"' % DC
        if not os.path.isfile(msexshell_path1):
            msg = 'Cannot find Exchange Management Shell'
            return self._log_exception('warn', 'UpdateRecipient: %s' % msg)
 
        try:
            r, executable = win32api.FindExecutable(ps_cmd)
            process = subprocess.Popen(cmd, shell=False,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
        except pywintypes.error:
            msg = 'Powershell_cerebrum not found!'
            return self._log_exception('warn', 'UpdateRecipient: %s' % msg)
        except OSError, e:
            msg = 'Execution of Update-Recipient failed: %s' % (e)
            return self._log_exception('warn', msg)
        else:
            # give it time to respond
            process.wait()
            stdoutput = str(process.communicate()).replace("\\r\\n","")
            if process.returncode == 0:
                logging.debug("Update-Recipient for %s succesfull" % sAMAccountname)
                return (True, 'UpdateRecipient')
            else:
                msg = 'Update-Recipient for %s FAILED with error message %s' % (
                    sAMAccountname, stdoutput)
                return self._log_exception('warn', msg)
 
 
 
class Exchange_2003(ADObject):
    """
    Class for manipulating mailboxes in exchange versions 2003 and earlier!
    IMPORTANT: Exchange System Manager tools must be installed for this class 
    to work.
    """  
 
    def __init__(self, *args, **kwargs):
        super(Exchange, self).__init__(*args, **kwargs)
 
 
    def createMDB(self):
        """Creates a mailbox. Must bind to object. Do not seem like the method 
        returns other than None in case of failure or success, so no 
        errorchecking is performed."""
	MDB = self.Object.Get('HomeMDB') 
        if MDB == None:
            logging.debug("No mailbox registered for %s." %
                          (self.distinguishedName))
            return [False, 'No Mailbox registered in AD']
	else:
            ret = self.Object.CreateMailbox(MDB)
            logging.debug("Creating mailbox on %s for %s, return:%s" %
                          (MDB, self.distinguishedName, ret))
	    return [True, 'createMDB']
 
 
    def deleteMDB(self):
	"""Deletes a mailbox. Must bind to object. No proper returnvalue""" 
        ret = self.Object.DeleteMailbox()
        logging.debug("Deleting mailbox on for %s." % self.distinguishedName)
        return [True, 'deleteMDB']
 
 
    def checkMDB(self):
        """Returns True/False if HomeMDB attribute is registered in AD.""" 
        if self.Object.Get('HomeMDB') == None:
            return False
	else:
            return True 
 
 
    def moveMDB(self, MDB):
	"""Must bind to object. Moves a mailbox from one location to another, 
           also used for renaming of a mailbox."""
 
	CurrentMDB = self.Object.Get('HomeMDB')
	if CurrentMDB == None:
            return [False, 'No mailbox to move']
	else:
            ret = self.Object.MoveMailBox(MDB)
            logging.debug("Creating mailbox on %s for %s, return:%s." %
                          (MDB, self.distinguishedName, ret))
	    return [True, 'moveMDB']