def create_shared_mailbox(self, name): """Create a new shared mailbox in Exchange. :type name: string :param name: The mailbox name. :rtype: bool :return: Return True if success. :raise ExchangeException: If the command failed to run for some reason """ assert (isinstance(self.exchange_commands, dict) and 'execute_on_create_shared_mailbox' in self.exchange_commands) cmd_template = string.Template( self.exchange_commands['execute_on_create_shared_mailbox']) cmd = self._generate_exchange_command( cmd_template.safe_substitute(name=self.escape_to_string(name))) try: out = self.run(cmd) except PowershellException: raise ExchangeException( 'Could not create shared mailbox for {name}'.format(name=name)) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def new_mailbox(self, uname, display_name, first_name, last_name, primary_address, db=None, ou=None): """Create a new mailbox in Exchange. :type uname: string :param uname: The users username. :type display_name: string :param display_name: The users full name. :type first_name: string :param first_name: The users given name. :type last_name: string :param last_name: The users family name. :type primary_address: string :param primary_address: The users primary email address. :type db: string :param db: The DB the user should reside on. :type ou: string :param ou: The container that the mailbox should be organized in. :rtype: bool :return: Return True if success. :raise ExchangeException: If the command failed to run for some reason """ assert (isinstance(self.exchange_commands, dict) and 'execute_on_new_mailbox' in self.exchange_commands) cmd_template = string.Template( self.exchange_commands['execute_on_new_mailbox']) cmd = self._generate_exchange_command( cmd_template.safe_substitute( uname=self.escape_to_string(uname), primary_address=self.escape_to_string(primary_address), display_name=self.escape_to_string(display_name), first_name=self.escape_to_string(first_name), last_name=self.escape_to_string(last_name))) try: out = self.run(cmd) except PowershellException: raise ExchangeException('Could not create mailbox for %s' % uname) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_mailbox_quota(self, uname, soft, hard): """Set the quota for a particular mailbox. :type uname: string :param uname: The username to look up associated mailbox by. :type soft: int :param soft: The soft-quota limit in MB. :type hard: int :param hard: The hard-quota limit in MB. :raise ExchangeException: If the command failed to run for some reason.""" cmd = self._generate_exchange_command( 'Set-Mailbox', { 'Identity': uname, 'IssueWarningQuota': '"%d MB"' % int(soft), 'ProhibitSendReceiveQuota': '"%d MB"' % int(hard), 'ProhibitSendQuota': '"%d MB"' % int(hard) }, ('UseDatabaseQuotaDefaults:$false', )) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def get_group_info(self, attributes, ou=None): """Get information about the distribution group in Exchange. :type attributes: list(string) :param attributes: Which attributes we want to return. :type ou: string :param ou: The organizational unit to look in. :raises ExchangeException: Raised if the command fails to run.""" if ou: f_org = '-OrganizationalUnit \'%s\'' % ou else: f_org = '' cmd = self._generate_exchange_command( '''Get-DistributionGroup %s -ResultSize Unlimited | Select %s''' % (f_org, ', '.join(attributes))) # TODO: Do we really need to add that ;? We can't have it here... json_wrapped = '''if ($str = %s | ConvertTo-Json) { $str -replace '$', ';' }''' % cmd[:-1] out = self.run(json_wrapped) try: ret = self.get_output_json(out, dict()) except ValueError, e: raise ExchangeException('No groups exists?: %s' % str(e))
def set_mailbox_names(self, uname, first_name, last_name, full_name): """Set a users name. :type uname: string :param uname: The uname to select account by. :type first_name: string :param first_name: The persons first name. :type last_name: string :param last_name: The persons last name. :type full_name: string :param full_name: The persons full name, to use as display name. :raises ExchangeException: Raised upon errors.""" # TODO: When empty strings as args to the keyword args are handled # appropriatly, change this back. args = [ "FirstName %s" % self.escape_to_string(first_name), "LastName %s" % self.escape_to_string(last_name), "DisplayName %s" % self.escape_to_string(full_name) ] cmd = self._generate_exchange_command('Set-User', {'Identity': uname}, (' -'.join(args), )) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_distgroup_member_restrictions(self, gname, join='Closed', part='Closed'): """Set the member restrictions on a Distribution Group. Default is 'Closed'-state. :type gname: string :param gname: The groups name. :type join: str :param join: Set MemberJoinRestriction to 'Open', 'Closed' or 'ApprovalRequired'. :type part: str :param part: Set MemberPartApprovalRequiredion to 'Open', 'Closed' or 'ApprovalRequired'. :raise ExchangeException: If the command cannot be run, raise.""" # TBD: Enforce constraints on join- and part-restrictions? params = {'Identity': gname} if join: params['MemberJoinRestriction'] = join if part: params['MemberDepartRestriction'] = part cmd = self._generate_exchange_command('Set-DistributionGroup', params) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_forward(self, uname, address): """Set forwarding address for a mailbox. :type uname: string :param uname: The users username. :type address: String or None :param address: The forwarding address to set. :raises ExchangeException: If the command fails to run.""" if not address: cmd = self._generate_exchange_command( 'Set-Mailbox', {'Identity': uname}, ('ForwardingSmtpAddress $null', )) else: cmd = self._generate_exchange_command( 'Set-Mailbox', { 'Identity': uname, 'ForwardingSmtpAddress': address }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def add_distgroup_member(self, gname, member): """Add member to a distgroup. :type gname: string :param gname: The groups name. :type member: string :param member: The members name. :rtype: bool :return: Returns True if the operation resulted in an update, False if it does not. :raise ExchangeException: If it fails to run.""" cmd = self._generate_exchange_command('Add-DistributionGroupMember', { 'Identity': gname, 'Member': member }, ('BypassSecurityGroupManagerCheck', )) out = self.run(cmd) if 'stderr' in out: # If this matches, we have performed a duplicate operation. Notify # the caller of this trough raise. if 'MemberAlreadyExistsException' in out['stderr']: raise AlreadyPerformedException else: raise ExchangeException(out['stderr']) else: return True
def set_spam_settings(self, uname, level, action): """Set spam settings for a user. :type uname: string :param uname: The username. :type level: int :param level: The spam level to set. :type action: string :param action: The spam action to set. :raises ExchangeException: If the command fails to run.""" assert (isinstance(self.exchange_commands, dict) and 'execute_on_set_spam_settings' in self.exchange_commands) cmd_template = string.Template( self.exchange_commands['execute_on_set_spam_settings']) args = { 'uname': self.escape_to_string(uname), 'level': self.escape_to_string(level), 'action': self.escape_to_string(action) } cmd = self._generate_exchange_command( cmd_template.safe_substitute(args)) try: out = self.run(cmd) except PowershellException, e: raise ExchangeException(str(e))
def new_group(self, gname, ou=None): """Create a new mail enabled security group. :type gname: string :param gname: The groups name. :type ou: string :param ou: The container the group should be organized in. :raises ExchangeException: Raised if the command fails to run. """ param = { 'Name': gname, 'GroupCategory': 'Security', 'GroupScope': 'Universal', 'Server': self.resource_ad_server } if ou: param['Path'] = ou cmd = self._generate_exchange_command('New-ADGroup', param, ('Credential $cred', )) param = { 'Identity': '"CN=%s,%s"' % (gname, ou), 'DomainController': self.resource_ad_server } nva = ('Confirm:$false', ) cmd += self._generate_exchange_command('Enable-Distributiongroup', param, nva) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_distgroup_description(self, gname, description): """Set a distributiongroups description. :type gname: string :param gname: The groups name. :type description: str :param description: The groups description. :raises ExchangeException: If the command fails to run.""" cmd = self._generate_exchange_command( 'Set-Group', {'Identity': gname}, ('Notes %s' % self.escape_to_string(description.strip()), )) # TODO: On the line above, we strip of the leading and trailing # whitespaces. We need to do this, as leading and trailing whitespaces # triggers an error when we set the "description" when creating the # mailboxes. But, we don't need to do this if we change the description # after the mailbox has been created! Very strange behaviour. Think # about this and fix it (whatever that means). out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_mailbox_names(self, uname, first_name, last_name, full_name): """Set a users name @type uname: string @param uname: The uname to select account by @type first_name: string @param first_name: The persons first name @type last_name: string @param last_name: The persons last name @type full_name: string @param full_name: The persons full name, to use as display name @raises ExchangeException: Raised upon errors """ cmd = self._generate_exchange_command( 'Set-User', { 'Identity': uname, 'FirstName': first_name, 'LastName': last_name, 'DisplayName': full_name }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def new_mailbox(self, uname): """Create a new mailbox in Exchange. @type uname: string @param uname: The users username @rtype: bool @return: Return True if success @raise ExchangeException: If the command failed to run for some reason """ cmd = self._generate_exchange_command('Enable-Mailbox', {'Identity': uname}) # We set the mailbox as hidden, in the same call. We won't # risk exposing in the really far-fetched case that the integration # crashes in between new-mailbox and set-mailbox. cmd += '; ' + self._generate_exchange_command( 'Set-Mailbox', { 'Identity': uname, 'HiddenFromAddressListsEnabled': True }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def remove_mailbox(self, uname): """Remove a mailbox and it's linked account from Exchange. :type uname: string :param uname: The users username. :raises ExchangeException: If the command fails to run. """ assert (isinstance(self.exchange_commands, dict) and 'execute_on_remove_mailbox' in self.exchange_commands) cmd_template = string.Template( self.exchange_commands['execute_on_remove_mailbox']) cmd = self._generate_exchange_command( cmd_template.safe_substitute(uname=self.escape_to_string(uname))) try: out = self.run(cmd) except PowershellException: raise ExchangeException('Could not remove mailbox for %s' % uname) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def delete_shared_mailbox(self, name): """Remove a shared mailbox. :type name: string :param name: The mailbox name :raises ExchangeException: If the command fails to run. """ assert (isinstance(self.exchange_commands, dict) and 'execute_on_delete_shared_mailbox' in self.exchange_commands) cmd_template = string.Template( self.exchange_commands['execute_on_delete_shared_mailbox']) cmd = self._generate_exchange_command( cmd_template.safe_substitute(name=self.escape_to_string(name))) try: out = self.run(cmd) except PowershellException: raise ExchangeException( 'Could not remove shared mailbox for {name}'.format(name=name)) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def remove_group(self, gname): """Remove a mail enabled securitygroup. :type gname: string :param gname: The groups name. :raises ExchangeException: Raised if the command fails to run.""" cmd = self._generate_exchange_command( 'Remove-ADGroup', {'Identity': gname}, ('Confirm:$false', 'Credential $cred')) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def remove_roomlist(self, gname): """Remove a roomlist. :type gname: string :param gname: The roomlists name. :raise ExchangeException: If the command cannot be run, raise.""" cmd = self._generate_exchange_command('Remove-DistributionGroup', {'Identity': gname}, ('Confirm:$false', )) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def remove_mailbox(self, uname): """Remove a mailbox and it's linked account from Exchange. :type uname: string :param uname: The users username. :raises ExchangeException: If the command fails to run. """ cmd = self._generate_exchange_command('Remove-Mailbox', {'Identity': uname}, ('Confirm:$false', )) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def get_group_members(self, gname): """Return the members of a group. :type gname: string :param gname: The groups name. :raises ExchangeException: Raised if the command fails to run.""" # Jeg er mesteren!!!!!11 cmd = self._generate_exchange_command( '$m = @(); $m += Get-ADGroupMember %s -Credential $cred | ' % gname + 'Select -ExpandProperty Name; ConvertTo-Json $m') out = self.run(cmd) try: ret = self.get_output_json(out, dict()) except ValueError, e: raise ExchangeException('No group members in %s?: %s' % (gname, e))
def set_distgroup_manager(self, gname, addr): """Set the manager of a distribution group. :type gname: string :param gname: The groups name. :type addr: str :param uname: The e-mail address which manages this group. :raise ExchangeException: If the command cannot be run, raise.""" cmd = self._generate_exchange_command('Set-DistributionGroup', { 'Identity': gname, 'ManagedBy': addr }, ('BypassSecurityGroupManagerCheck', )) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_distgroup_address_policy(self, gname, enabled=False): """Enable or disable the AddressPolicy for the Distribution Group. :type gname: string :param gname: The groups name. :type enabled: bool :param enabled: Enable or disable address policy. :raise ExchangeException: If the command cannot be run, raise.""" cmd = self._generate_exchange_command( 'Set-DistributionGroup', { 'Identity': gname, 'EmailAddressPolicyEnabled': enabled }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_group_display_name(self, gname, dn): """Set a groups display name. :type gname: string :param gname: The groups name. :type dn: str :param dn: display name. :raises ExchangeException: If the command fails to run.""" cmd = self._generate_exchange_command('Set-ADGroup', { 'Identity': gname, 'DisplayName': dn }, ('Credential $cred', )) # TODO: Verify how this is to be done out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_distgroup_primary_address(self, gname, address): """Set the primary-address of a Distribution Group. :type gname: string :param gname: The groups name. :type address: string :param address: The primary address. :raise ExchangeException: If the command cannot be run, raise.""" # TODO: We want to diable address policy while doing htis? cmd = self._generate_exchange_command('Set-DistributionGroup', { 'Identity': gname, 'PrimarySmtpAddress': address }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_distgroup_visibility(self, gname, visible=True): """Set the visibility of a DistributionGroup in the address books. :type gname: string :param gname: The group name :type visible: bool :param visible: Should the group be visible? Defaults to true :raises ExchangeException: If the command fails to run.""" cmd = self._generate_exchange_command( 'Set-DistributionGroup', { 'Identity': gname, 'HiddenFromAddressListsEnabled': visible }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_local_delivery(self, uname, local_delv): """Set local delivery for a mailbox. :type uname: string :param uname: The users username. :type local_delivery: bool :param local_delivery: Enable or disable local delivery. :raises ExchangeException: If the command fails to run.""" cmd = self._generate_exchange_command( 'Set-Mailbox', { 'Identity': uname, 'DeliverToMailboxAndForward': local_delv }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def set_mailbox_visibility(self, uname, visible=False): """Set the visibility of a mailbox in the address books. :type uname: string :param uname: The username associated with the mailbox. :type enabled: bool :param enabled: To show or hide the mailbox. Default hide. :raises ExchangeException: If the command fails to run.""" cmd = self._generate_exchange_command( 'Set-Mailbox', { 'Identity': uname, 'HiddenFromAddressListsEnabled': not visible }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def remove_distgroup_member(self, gname, member): """Remove a member from a distributiongroup. :type gname: string :param gname: The groups name. :type member: string :param member: The members username. :raises ExchangeException: If it fails.""" # TODO: Add DomainController arg. cmd = self._generate_exchange_command( 'Remove-DistributionGroupMember', { 'Identity': gname, 'Member': member }, ('BypassSecurityGroupManagerCheck', 'Confirm:$false')) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def get_mailbox_info(self, attributes): """Get information about the mailboxes in Exchange. :type attributes: list(string) :param attributes: Which attributes we want to return. :raises ExchangeException: Raised if the command fails to run.""" # TODO: Filter by '-Filter {IsLinked -eq "True"}' on get-mailbox. cmd = self._generate_exchange_command( '''Get-Mailbox -ResultSize Unlimited | Select %s''' % ', '.join(attributes)) # TODO: Do we really need to add that ;? We can't have it here... json_wrapped = '''if ($str = %s | ConvertTo-Json) { $str -replace '$', ';' }''' % cmd[:-1] out = self.run(json_wrapped) try: ret = self.get_output_json(out, dict()) except ValueError, e: error = '%s\n%s' % (str(e), str(out)) raise ExchangeException('No mailboxes exists?: %s' % error)
def set_mailbox_address_policy(self, uname, enabled=False): """Set the EmailAddressPolicEnabled for a mailbox. @type uname: string @param uname: The username to look up associated malbox by @type enabled: bool @param enabled: Enable or disable the AddressPolicy @raise ExchangeException: If the command failed to run for some reason """ cmd = self._generate_exchange_command( 'Set-Mailbox', { 'Identity': uname, 'EmailAddressPolicyEnabled': enabled }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True
def remove_mailbox_addresses(self, uname, addresses): """Remove email addresses from a mailbox. :type uname: string :param uname: The user name to look up associated mailbox by. :type addresses: list :param addresses: A list of addresses to remove. :raise ExchangeException: If the command failed to run for some reason.""" addrs = {'remove': addresses} cmd = self._generate_exchange_command('Set-Mailbox', { 'Identity': uname, 'EmailAddresses': addrs }) out = self.run(cmd) if 'stderr' in out: raise ExchangeException(out['stderr']) else: return True