Example #1
0
    def test_now_validInput(self):
        """
        Tests that now performs as expected when valid input is provided to the formatting function.

        """
        is_valid_date = {}
        date_type = {}

        # Matches 1900-01-01 00:00 - 2999-12-31 23:59
        date_type[0] = '%Y-%m-%d %H:%M'
        matchDate = "(19|2[0-9])\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"
        matchTime = "(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})"
        is_valid_date[0] = re.compile("^%s %s$" %(matchDate, matchTime))

        # Matches 01-01-1900 00:00 - 12-31-2999 23:59
        date_type[0] = '%m-%d-%Y %H:%M'
        matchDate = "(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])-(19|2[0-9])\d\d"
        is_valid_date[0] = re.compile("^%s %s$" %(matchDate, matchTime))

        for type in date_type:
            # Check for a valid search result (no result will not have the group() method)
            try:
                is_valid_date[type].search(nixcommon.now(date_type[type])).group(0)
            except AttributeError:
                assert False, "Invalid datetime stamp. Regex search did not return a result."
Example #2
0
    def write(self, config_dict=None):
        """
        Writes the config dictionary to disc.

        """
        from lib import nixcommon

        root_values = ""
        section_data = ""

        # Make sure the config is loaded
        if config_dict:
            self.config = config_dict
        elif not self.config:
            raise SSLConfigError("Config not loaded.")

        config_text = nixcommon.comment(
            "%s -- Generated on %s by %s\n\n" % (self.file_path, nixcommon.now(), nixcommon.whoAmI())
        )
        keys = self.config.keys()
        keys.sort()

        # Use the dict keys to generate the root and section data
        for key in keys:
            if type(self.config[key]) == str or type(self.config[key]) == unicode:
                root_values += "%s\t= %s\n" % (key, self.config[key])
            else:
                section_data += "\n[ %s ]\n" % key
                section_data += "".join(
                    sorted(list("%s\t= %s\n" % (pair_key, self.config[key][pair_key]) for pair_key in self.config[key]))
                )

        config_text += "\n%s\n%s" % (root_values, section_data)

        super(SSLConfigParser, self).write(config_text)
Example #3
0
    def touch(self, path_to_file, text = '', header = 'Automatically generated at %s.' %nixcommon.now(), overwrite = False):
        """
        Outputs text to a file on the ESX server.
        :param path_to_file: String with the path to the target file on the server (include the file name).
        :param text: String with text to place in the target file.
        :param header: String with content for a 'comment' header at the top of the file.
        :param overwrite: Boolean.  Allows overwriting an existing file.  Defaults to ``False``.
        :return:
        """
        if not overwrite:
            def nullHandler(x,y): return
            file_check = 'ls "%s"' %path_to_file
            file_check_info = self._vmwareCommand(file_check, nullHandler)

            print file_check_info + "BOB"

            # This is to broad, it causes 'File exists!' on any error.
            if not file_check_info['return_code'] or file_check_info['stderr'][0].find('No such file or directory') == -1:
                raise FileError('File exits! (%s)' %path_to_file)

        if text:
            touch = 'cat <<EOF > "%s"\n%s\n\n%s\nEOF\n' %(path_to_file, nixcommon.comment(header), text)
        else:
            touch = 'touch "%s"' %path_to_file
        self._vmwareCommand(touch)
    #---

#---
Example #4
0
    def writeNTPConf(self, ntp_dict):
        """
        Writes a ntp configuration dictionary to the loaded file.

        :param ntp_dict: NTP configuration dictionary

        """
        import string

        ntp_config = nixcommon.comment("%s -- Generated on %s by %s\n\n" %(self.file, nixcommon.now(),
                                                                           nixcommon.whoAmI()))
        for attribute in ntp_dict:
            for values in ntp_dict[attribute]:
                ntp_config += "%s %s\n" %(attribute, string.join(values))
            ntp_config += '\n'

        try:
            ntp_config_file = open(self.file, 'wb')
        except IOError:
            raise nixexceptions.FileNotWriteable(self.file)

        ntp_config_file.write(ntp_config)
        ntp_config_file.close()

        return
    #---
Example #5
0
    def writeKrb5ACL(self, acls, comments = ''):
        """
        Writes a list of tuples consisting of the principal, operation mask and operation target to a Kerberos ACL.
         
        :param acls: List of tuples (principal, operation_mask, operation_target).
        :param comments: Comments to place at the top of the file.

        """
        try:
            krb5ACL = open(self.file, 'wb')
        except IOError:
            raise nixexceptions.FileNotWriteable(self.file)
            
        aclsTxt = nixcommon.comment("%s -- Generated on %s by %s\n\n%s\n" %(self.file, nixcommon.now(),
                                                                            nixcommon.whoAmI(), comments))
        
        for (principal, operation_mask, operation_target) in acls:
            aclsTxt += "%s\t%s\t%s\n" %(principal , operation_mask, operation_target)
            
        krb5ACL.write(aclsTxt)
        krb5ACL.close()

        return
Example #6
0
    def writeKrb5Conf(self, krb5_dict, comments = ''):
        """
        Writes a Python dictionary back to krb5.conf.  If desired *comments* may be set to a string or list of strings
        which will print comments at the top of the file.

        :param krb5_dict: Dictionary to convert to a Kerberos config file.
        :param comments: String or list of strings to use as a comment at top of the file.

        """
        try:
            krb5Conf = open(self.file, 'wb')
        except IOError:
            raise nixexceptions.FileNotWriteable(self.file)

        confTxt = nixcommon.comment("%s -- Generated on %s by %s\n\n%s\n" %(self.file, nixcommon.now(),
                                                                            nixcommon.whoAmI(), comments))
                
        # Loop through the dictionary, creating text we can write to the file
        for section in krb5_dict:
            confTxt += '[' + section + ']\n'
            
            for line in krb5_dict[section]:
                lineType = type(krb5_dict[section][line])
                
                # Multi-line segment
                if lineType == dict:
                    confTxt += '\t' + line + ' = {\n'
                    for multiLine in krb5_dict[section][line]:
                        confTxt += '\t\t' + multiLine + ' = ' + krb5_dict[section][line][multiLine] + '\n'
                    confTxt += '\t}\n'
                # Single-line segment
                elif lineType == str:
                    confTxt += '\t' + line + ' = ' + krb5_dict[section][line] + '\n'
                    
            confTxt += '\n'

        krb5Conf.write(confTxt)
        krb5Conf.close()

        return 
Example #7
0
    def write(self, ntp_dict = None):
        """
        Writes a ntp configuration dictionary to the loaded file.

        :param ntp_dict: NTP configuration dictionary

        """
        from lib import nixcommon
        import string

        if ntp_dict:
            self.config = ntp_dict
        elif not self.config:
            raise NTPConfigDataError('Config not loaded.')

        ntp_config = nixcommon.comment("%s -- Generated on %s by %s\n\n" %(self.file_path, nixcommon.now(),
                                                                           nixcommon.whoAmI()))
        for attribute in self.config:
            for values in self.config[attribute]:
                ntp_config += "%s %s\n" %(attribute, string.join(values))
            ntp_config += '\n'

        nixconfigparser.NixConfigParser.write(self,ntp_config)

        return
    #---
#---
Example #8
0
        con.prints('Some applications were not installed by napkginstall!')
        exit(3)
else:
    log.info('Writing paths config')
    # Store the paths to their config file
    app_path_file = "%s/conf/paths.py" %NA_ROOT

    # Automated install overwrites by default
    if os.path.exists(app_path_file) and na_run_from:
        log.debug('Automatically overwrote paths file (na_run_from is set)')
        os.remove(app_path_file)

    # User is running the script, ask them questions
    elif os.path.exists(app_path_file) and not na_run_from:
        if con.askBoolQuestion('Should I overwrite ' + app_path_file):
            log.debug('Overwrote the paths file at user\'s request')
            os.remove(app_path_file)
        else:
            log.debug('Kept existing config, at user\'s request')
            con.prints('Ok, keeping your existing file!')
            exit(0)

    paths_file = nixcommon.comment("%s -- Generated on %s by %s" %(app_path_file, nixcommon.now(),
                                                                           nixcommon.whoAmI()))

    con.prints('Writing path config to %s... ' %app_path_file, no_newline=True)
    nixcommon.createTextFile(app_path_file, "%s\n\n%s" %(paths_file,''.join(app_locations)))
    log.info('PathBuilder complete')
    con.prints('Done.')
    exit(0)