• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python fileutils.rotateFile函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中spacewalk.common.fileutils.rotateFile函数的典型用法代码示例。如果您正苦于以下问题:Python rotateFile函数的具体用法?Python rotateFile怎么用?Python rotateFile使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了rotateFile函数的17个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: writeRhnCert

def writeRhnCert(options, cert):
    if os.path.exists(DEFAULT_RHN_CERT_LOCATION):
        fileutils.rotateFile(DEFAULT_RHN_CERT_LOCATION, depth=5)
    fo = open(DEFAULT_RHN_CERT_LOCATION, 'w+b')
    fo.write(cert)
    fo.close()
    options.rhn_cert = DEFAULT_RHN_CERT_LOCATION
开发者ID:aronparsons,项目名称:spacewalk,代码行数:7,代码来源:rhn_satellite_activate.py


示例2: writeRhsmManifest

def writeRhsmManifest(options, manifest):
    if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
        fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
    fo = open(DEFAULT_RHSM_MANIFEST_LOCATION, 'w+b')
    fo.write(manifest)
    fo.close()
    options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
开发者ID:phurrelmann,项目名称:spacewalk,代码行数:7,代码来源:rhn_satellite_activate.py


示例3: writeRhsmManifest

def writeRhsmManifest(options, manifest):
    if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
        fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
    fo = open(DEFAULT_RHSM_MANIFEST_LOCATION, 'w+b')
    fo.write(manifest)
    fo.close()
    # Delete from temporary location
    if options.manifest_refresh:
        os.unlink(options.manifest)
    options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
开发者ID:lhellebr,项目名称:spacewalk,代码行数:10,代码来源:rhn_satellite_activate.py


示例4: copyFiles

def copyFiles(options):
    """ copies SSL cert and GPG key to --pub-tree if not in there already
        existence check should have already been done.
    """

    pubDir = cleanupAbsPath(options.pub_tree or DEFAULT_APACHE_PUB_DIRECTORY)

    def copyFile(file0, file1):
        if not os.path.exists(os.path.dirname(file1)):
            sys.stderr.write("ERROR: directory does not exist:\n       %s\n"
                             % os.path.dirname(file1))
            sys.exit(errnoBadPath)
        if not os.path.exists(file0):
            sys.stderr.write("ERROR: file does not exist:\n       %s\n"
                             % file0)
            sys.exit(errnoCANotFound)
        sys.stderr.write("""\
  Coping file into public directory tree:
    %s to
    %s
""" % (file0, file1))
        shutil.copy(file0, file1)

    # CA SSL cert
    if not options.no_ssl and options.ssl_cert:
        writeYN = 1
        dest = os.path.join(pubDir, os.path.basename(options.ssl_cert))
        if os.path.dirname(options.ssl_cert) != pubDir:
            if os.path.isfile(dest) \
              and getFileChecksum('md5', options.ssl_cert) != getFileChecksum('md5', dest):
                rotateFile(dest, options.verbose)
            elif os.path.isfile(dest):
                writeYN = 0
            if writeYN:
                copyFile(options.ssl_cert, dest)

    # corp GPG keys
    if not options.no_gpg and options.gpg_key:
        for gpg_key in options.gpg_key.split(","):
            writeYN = 1
            dest = os.path.join(pubDir, os.path.basename(gpg_key))
            if os.path.dirname(gpg_key) != pubDir:
                if os.path.isfile(dest) \
                  and getFileChecksum('md5', gpg_key) != getFileChecksum('md5', dest):
                    rotateFile(dest, options.verbose)
                elif os.path.isfile(dest):
                    writeYN = 0
                if writeYN:
                    copyFile(gpg_key, dest)
开发者ID:jdobes,项目名称:spacewalk,代码行数:49,代码来源:rhn_bootstrap.py


示例5: updateDir

    def updateDir(self, newdir=None, verbosity=0):
        """ changes the CA configuration file's directory setting (if need be)
            in place. Touches nothing else.
        """

        if self.updateLegacy(newdir):
            return

        try:
            fo = open(self.filename, 'r')
        except:
            return

        olddir = ''
        if newdir is None:
            newdir = os.path.dirname(self.filename)

        newfile = ""
        hit_CA_defaultYN = 0

        line = fo.readline()
        while line:
            if string.strip(line) == '[ CA_default ]':
                # we don't care much until we hit this label
                hit_CA_defaultYN = 1
            if hit_CA_defaultYN:
                vector = string.split(line, '=')
                if len(vector) == 2:
                    key, value = vector
                    if string.strip(key) == 'dir':
                        value = string.strip(value)
                        olddir = value
                        line = '%s= %s\n' % (key, newdir)
                        hit_CA_defaultYN = 0
                        if newdir == olddir:
                            # nothing to do
                            return
            newfile = newfile + line
            line = fo.readline()

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity>=0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename),
                                              os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(newfile)
        fo.close()
        os.chmod(self.filename, 0600)
开发者ID:NehaRawat,项目名称:spacewalk,代码行数:51,代码来源:sslToolConfig.py


示例6: genPrivateCaKey

def genPrivateCaKey(password, d, verbosity=0, forceYN=0):
    """ private CA key generation """

    gendir(d['--dir'])
    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))

    if not forceYN and os.path.exists(ca_key):
        sys.stderr.write("""\
ERROR: a CA private key already exists:
       %s
       If you wish to generate a new one, use the --force option.
""" % ca_key)
        sys.exit(errnoGeneralError)

    args = ("/usr/bin/openssl genrsa -passout pass:%s %s -out %s 2048"
            % ('%s', CRYPTO, repr(cleanupAbsPath(ca_key))))

    if verbosity >= 0:
        print("Generating private CA key: %s" % ca_key)
        if verbosity > 1:
            print("Commandline:", args % "PASSWORD")
    try:
        rotated = rotateFile(filepath=ca_key, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" \
                  % (d['--ca-key'], os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenPrivateCaKeyException("Certificate Authority private SSL "
                                       "key generation failed:\n%s\n%s"
                                       % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(ca_key, int('0600',8))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:49,代码来源:rhn_ssl_tool.py


示例7: genServerKey

def genServerKey(d, verbosity=0):
    """ private server key generation """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))
    gendir(serverKeyPairDir)

    server_key = os.path.join(serverKeyPairDir,
                              os.path.basename(d['--server-key']))

    args = ("/usr/bin/openssl genrsa -out %s 2048"
            % (repr(cleanupAbsPath(server_key))))

    # generate the server key
    if verbosity >= 0:
        print("\nGenerating the web server's SSL private key: %s" % server_key)
        if verbosity > 1:
            print("Commandline:", args)

    try:
        rotated = rotateFile(filepath=server_key, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" % (d['--server-key'],
                                          os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenServerKeyException("web server's SSL key generation failed:\n%s\n%s"
                                % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(server_key, int('0600',8))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:46,代码来源:rhn_ssl_tool.py


示例8: save

    def save(self, d, caYN=0, verbosity=0):
        """ d == commandline dictionary """

        mapping = {
                '--set-country'     : 'C',
                '--set-state'       : 'ST',
                '--set-city'        : 'L',
                '--set-org'         : 'O',
                '--set-org-unit'    : 'OU',
                '--set-common-name' : 'CN', # these two will never occur at the
                '--set-hostname'    : 'CN', # same time
                '--set-email'       : 'emailAddress',
                  }

        rdn = {}
        for k in d.keys():
            if mapping.has_key(k):
                rdn[mapping[k]] = string.strip(d[k])

        openssl_cnf = ''
        if caYN:
            openssl_cnf = CONF_TEMPLATE_CA % (
              os.path.dirname(self.filename)+'/',
              gen_req_distinguished_name(rdn),
              )
        else:
            openssl_cnf = CONF_TEMPLATE_SERVER \
              % (gen_req_distinguished_name(rdn), gen_req_alt_names(d, rdn['CN']))

        try:
            rotated = rotateFile(filepath=self.filename,verbosity=verbosity)
            if verbosity>=0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename),
                                              os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(openssl_cnf)
        fo.close()
        os.chmod(self.filename, 0600)
        return openssl_cnf
开发者ID:NehaRawat,项目名称:spacewalk,代码行数:41,代码来源:sslToolConfig.py


示例9: save

    def save(self, d, caYN=0, verbosity=0):
        """ d == commandline dictionary """

        mapping = {
            "--set-country": "C",
            "--set-state": "ST",
            "--set-city": "L",
            "--set-org": "O",
            "--set-org-unit": "OU",
            "--set-common-name": "CN",  # these two will never occur at the
            "--set-hostname": "CN",  # same time
            "--set-email": "emailAddress",
        }

        rdn = {}
        for k in d.keys():
            if mapping.has_key(k):
                rdn[mapping[k]] = string.strip(d[k])

        openssl_cnf = ""
        if caYN:
            openssl_cnf = CONF_TEMPLATE_CA % (os.path.dirname(self.filename) + "/", gen_req_distinguished_name(rdn))
        else:
            openssl_cnf = CONF_TEMPLATE_SERVER % gen_req_distinguished_name(rdn)

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity >= 0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename), os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, "w")
        fo.write(openssl_cnf)
        fo.close()
        os.chmod(self.filename, 0600)
        return openssl_cnf
开发者ID:pombredanne,项目名称:spacewalk-1,代码行数:36,代码来源:sslToolConfig.py


示例10: main

def main():
    """ main routine
        1    general failure
        10   general sanity check failure (to include a remedial cert
             version check)
        11   expired!
        12   certificate version fails remedially
        13   certificate missing in manifest
        14   manifest signature incorrect
        15   cannot load mapping files
        16   manifest download failed
        17   manifest refresh failed
        30   local activation failure

        90   not registered to rhsm
        91   enabling sat repo failed

        127  general unknown failure (not really mapped yet)

        FIXME - need to redo how we process error codes - very manual
    """
    # pylint: disable=R0911

    options = processCommandline()

    if not cdn_activation:
        writeError("Package spacewalk-backend-cdn has to be installed for using this tool.")
        sys.exit(1)

    # CDN Deactivation
    if options.deactivate:
        cdn_activation.Activation.deactivate()
        # Rotate the manifest to not have any currently used
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            fileutils.rotateFile(DEFAULT_RHSM_MANIFEST_LOCATION, depth=5)
            os.unlink(DEFAULT_RHSM_MANIFEST_LOCATION)
        return 0

    if options.rhn_cert:
        writeError("Activation with RHN Classic Satellite Certificate is deprecated.\nPlease obtain a Manifest for this"
                   " Satellite version via https://access.redhat.com/knowledge/tools/satcert, "
                   "and re-run this activation tool with option --manifest=MANIFEST-FILE.")
        sys.exit(1)

    if not options.manifest:
        if os.path.exists(DEFAULT_RHSM_MANIFEST_LOCATION):
            options.manifest = DEFAULT_RHSM_MANIFEST_LOCATION
            if options.manifest_info:
                cdn_activation.Activation.manifest_info(DEFAULT_RHSM_MANIFEST_LOCATION)
                return 0
            # Call regeneration API on Candlepin server
            if options.manifest_reconcile_request:
                log(0, "Requesting manifest regeneration...")
                ok = cdn_activation.Activation.refresh_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not ok:
                    writeError("Manifest regeneration failed!")
                    return 17
                log(0, "Manifest regeneration requested.")
                return 0
            # Get new refreshed manifest from Candlepin server
            if options.manifest_download:
                log(0, "Downloading manifest...")
                path = cdn_activation.Activation.download_manifest(
                    DEFAULT_RHSM_MANIFEST_LOCATION,
                    http_proxy=options.http_proxy,
                    http_proxy_username=options.http_proxy_username,
                    http_proxy_password=options.http_proxy_password)
                if not path:
                    writeError("Manifest download failed!")
                    return 16
                if options.manifest_refresh:
                    options.manifest = path
                else:
                    log(0, "New manifest saved to: '%s'" % path)
                    return 0
        else:
            writeError("No currently activated manifest was found. "
                       "Run the activation tool with option --manifest=MANIFEST.")
            return 1
    # Handle RHSM manifest
    try:
        cdn_activate = cdn_activation.Activation(options.manifest)
    except CdnMappingsLoadError, e:
        writeError(e)
        return 15
开发者ID:lhellebr,项目名称:spacewalk,代码行数:89,代码来源:rhn_satellite_activate.py


示例11: updateLegacy

    def updateLegacy(self, newdir=None, verbosity=1):
        """ in slightly older formatted ca_openssl.cnf files, there
            was no dir setting seperate from the database and serial
            settings. This function fixes that setup.

            Most of the time this function short-circuits early.
        """

        try:
            fo = open(self.filename, 'r')
        except:
            return

        if newdir is None:
            newdir = os.path.dirname(self.filename)

        newfile = ""
        in_CA_defaultYN = 0
        dirSetYN = 0

        line = fo.readline()
        while line:
            cleanLine = string.strip(line)

            # is this a label?
            isLabelYN = 0
            if cleanLine \
              and (cleanLine[0], cleanLine[-1]) == ('[',']'):
                isLabelYN = 1

            if cleanLine == '[ CA_default ]':
                # we don't care much until we hit this label
                in_CA_defaultYN = 1
            elif isLabelYN:
                in_CA_defaultYN = 0 # hit another label

            if in_CA_defaultYN:
                vector = string.split(line, '=')
                if len(vector) == 2:
                    key = string.strip(vector[0])
                    if key == 'dir':
                        # we should be OK - short-circuit
                        return
                    if key in ('database', 'serial'):
                        # we never hit a "dir" key
                        if not dirSetYN:
                            newfile = newfile + """\
dir                     = %s
database                = $dir/index.txt
serial                  = $dir/serial
""" % newdir
                            dirSetYN = 1
                        line = fo.readline()
                        continue

            newfile = newfile + line
            line = fo.readline()

        try:
            rotated = rotateFile(filepath=self.filename, verbosity=verbosity)
            if verbosity>=0 and rotated:
                print "Rotated: %s --> %s" % (os.path.basename(self.filename),
                                              os.path.basename(rotated))
        except ValueError:
            pass
        fo = open(self.filename, 'w')
        fo.write(newfile)
        fo.close()
        os.chmod(self.filename, 0600)

        return dirSetYN
开发者ID:NehaRawat,项目名称:spacewalk,代码行数:71,代码来源:sslToolConfig.py


示例12: writeClientConfigOverrides

def writeClientConfigOverrides(options):
    """ write our "overrides" configuration file
        This generated file is a configuration mapping file that is used
        to map settings in up2date and rhn_register when run through a
        seperate script.
    """

    up2dateConfMap = {
        # some are directly mapped, others are handled more delicately
        'http_proxy':           'httpProxy',
        'http_proxy_username':  'proxyUser',
        'http_proxy_password':  'proxyPassword',
        'hostname':             'serverURL',
        'ssl_cert':             'sslCACert',
        'no_gpg':               'useGPG',
    }

    _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap'))

    if not os.path.exists(_bootstrapDir):
        print "* creating '%s'" % _bootstrapDir
        os.makedirs(_bootstrapDir) # permissions should be fine

    d = {}
    if options.hostname:
        scheme = 'https'
        if options.no_ssl:
            scheme = 'http'
        d['serverURL'] = scheme + '://' + options.hostname + '/XMLRPC'
        d['noSSLServerURL'] = 'http://' + options.hostname + '/XMLRPC'
    
    # if proxy, enable it
    # if "", disable it
    if options.http_proxy:
        d['enableProxy'] = '1'
        d[up2dateConfMap['http_proxy']] = options.http_proxy
    else:
        d['enableProxy'] = '0'
        d[up2dateConfMap['http_proxy']] = ""

    # if proxy username, enable auth proxy
    # if "", disable it
    if options.http_proxy_username:
        d['enableProxyAuth'] = '1'
        d[up2dateConfMap['http_proxy_username']] = options.http_proxy_username
        d[up2dateConfMap['http_proxy_password']] = options.http_proxy_password
    else:
        d['enableProxyAuth'] = '0'
        d[up2dateConfMap['http_proxy_username']] = ""
        d[up2dateConfMap['http_proxy_password']] = ""

    # CA SSL certificate is a bit complicated. options.ssl_cert may be a file
    # or it may be an RPM or it may be "", which means "try to figure it out
    # by searching through the --pub-tree on your own.
    _isRpmYN = processCACertPath(options)
    if not options.ssl_cert:
        sys.stderr.write("WARNING: no SSL CA certificate or RPM found in %s\n" % options.pub_tree)
        if not options.no_ssl:
            sys.stderr.write("         Fix it by hand or turn off SSL in the clients (--no-ssl)\n")
    _certname = os.path.basename(options.ssl_cert) or CA_CRT_NAME
    _certdir = os.path.dirname(DEFAULT_CA_CERT_PATH)
    if _isRpmYN:
        hdr = rhn_rpm.get_package_header(options.ssl_cert)
        # Grab the first file out of the rpm
        d[up2dateConfMap['ssl_cert']] = hdr[rhn_rpm.RPMTAG_FILENAMES][0] # UGLY!
    else:
        d[up2dateConfMap['ssl_cert']] = os.path.join(_certdir, _certname)
    d[up2dateConfMap['no_gpg']] = int(operator.truth(not options.no_gpg))

    writeYN = 1
    _overrides = cleanupAbsPath(os.path.join(_bootstrapDir, options.overrides))
    if os.path.exists(_overrides):
        if readConfigFile(_overrides) != d:
            # only back it up if different
            backup = rotateFile(_overrides, depth=5, verbosity=options.verbose)
            if backup and options.verbose>=0:
                print """\
* WARNING: if there were hand edits to the rotated (backed up) file,
           some settings may need to be migrated."""
        else:
            # exactly the same... no need to write
            writeYN = 0
            print """\
* client configuration overrides (old and new are identical; not written):
  '%s'\n""" % _overrides

    if writeYN:
        fout = open(_overrides, 'wb')
        # header
        fout.write("""\
# RHN Client (rhn_register/up2date) config-overrides file v4.0
#
# To be used only in conjuction with client_config_update.py
#
# This file was autogenerated.
#
# The simple rules:
#     - a setting explicitely overwrites the setting in
#       /etc/syconfig/rhn/{rhn_register,up2date} on the client system.
#     - if a setting is removed, the client's state for that setting remains
#.........这里部分代码省略.........
开发者ID:pombredanne,项目名称:spacewalk-1,代码行数:101,代码来源:rhn_bootstrap.py


示例13: legacyTreeFixup


#.........这里部分代码省略.........

    unknown = os.path.join(topdir, 'unknown')
    server_rpm_name = os.path.basename(d.get('--server-rpm', ''))
    serverKeyPairDir = None
    if '--set-hostname' in d:
        serverKeyPairDir = os.path.join(d['--dir'],
                                        getMachineName(d['--set-hostname']))

    while os.path.exists(unknown):
        # to avoid clashing with a possible "unknown" machinename
        unknown = unknown + '_'

    old_server_splat = os.path.join(topdir, 'server.')

    moveMessage = ""
    for ext in ('key', 'csr', 'crt'):
        if os.path.exists(old_server_splat+ext):
            gendir(unknown)
            files = glob.glob(old_server_splat+ext+'*')
            moved = []
            for f in files:
                # move the files to the "unknown" directory
                new_server_splat = os.path.join(unknown, os.path.basename(f))
                if not os.path.exists(new_server_splat):
                    shutil.copy2(f, new_server_splat)
                    os.unlink(f)
                    moved.append(f)

            #if files and verbosity:
            if moved:
                s = 'server.' + ext + '*'
                moveMessage = moveMessage + (
                  '  <BUILD_DIR>/%s --> <BUILD_DIR>/%s/%s\n'
                  % (s, os.path.basename(unknown), s))

    # move legacy server SSL RPMs. But if server_rpm_name is the same name
    # as the target RPM name, then we move the RPMs into the appropriate
    # machine name directory.
    for name in [LEGACY_SERVER_RPM_NAME1, LEGACY_SERVER_RPM_NAME2]:
        old_server_rpms = glob.glob(os.path.join(topdir, name+'-*-*.*.rpm'))
        movedYN = 0
        for old_rpm in old_server_rpms:
            targetDir = unknown
            old_hdr = get_package_header(old_rpm)
            if old_hdr and old_hdr['name'] == server_rpm_name and serverKeyPairDir:
                targetDir = serverKeyPairDir
            gendir(targetDir)
            # move the files to the targetDir directory
            new_rpm = os.path.join(targetDir, os.path.basename(old_rpm))
            if not os.path.exists(new_rpm):
                shutil.copy2(old_rpm, new_rpm)
                os.unlink(old_rpm)
                movedYN = 1
        if movedYN:
            s = name+'-*-*.{noarch,src}.rpm'
            moveMessage = moveMessage + """\
  <BUILD_DIR>/%s
      --> <BUILD_DIR>/%s/%s\n""" % (s, os.path.basename(targetDir), s)

    # I move the first 100 .pem files I find
    # if there is more than that... oh well
    movedYN = 0
    for i in range(100):
        serial = fixSerial(hex(i))
        oldPemPath = os.path.join(topdir, serial+'.pem')
        newPemPath = os.path.join(unknown, serial+'.pem')
        if os.path.exists(oldPemPath) and not os.path.exists(newPemPath):
            gendir(unknown)
            shutil.copy2(oldPemPath, newPemPath)
            os.unlink(oldPemPath)
            movedYN = 1
    if movedYN:
        moveMessage = moveMessage + (
          '  <BUILD_DIR>/HEX*.pem --> <BUILD_DIR>/%s/HEX*.pem\n'
          % os.path.basename(unknown))

    if moveMessage:
        sys.stdout.write('\nLegacy tree structured file(s) moved:\n%s'
                         % moveMessage)

    # move rhn-org-httpd-ssl-MACHINENAME-VERSION.*.rpm files to the
    # MACHINENAME directory! (an RHN 3.6.0 change)
    rootFilename = pathJoin(topdir, 'rhn-org-httpd-ssl-key-pair-')
    filenames = glob.glob(rootFilename+'*')
    for filename in filenames:
        # note: assuming version-rel is of that form.
        machinename = filename[len(rootFilename):]
        machinename = '-'.join(machinename.split('-')[:-2])
        serverKeySetDir = pathJoin(topdir, machinename)
        gendir(serverKeySetDir)
        fileto = pathJoin(serverKeySetDir, filename)
        if os.path.exists(fileto):
            rotateFile(filepath=fileto, verbosity=0)
        shutil.copy2(filename, fileto)
        os.unlink(filename)
        print("""\
Moved (legacy tree cleanup):
    %s
    ...moved to...
    %s""" % (filename, fileto))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:101,代码来源:rhn_ssl_tool.py


示例14: genServerCert

def genServerCert(password, d, verbosity=0):
    """ server cert generation and signing """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))

    genServerCert_dependencies(password, d)

    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))
    ca_cert = os.path.join(d['--dir'], os.path.basename(d['--ca-cert']))

    server_cert_req = os.path.join(serverKeyPairDir,
                                   os.path.basename(d['--server-cert-req']))
    server_cert = os.path.join(serverKeyPairDir,
                               os.path.basename(d['--server-cert']))
    ca_openssl_cnf = os.path.join(d['--dir'], CA_OPENSSL_CNF_NAME)

    index_txt = os.path.join(d['--dir'], 'index.txt')
    serial = os.path.join(d['--dir'], 'serial')

    try:
        os.unlink(index_txt)
    except:
        pass

    # figure out the serial file and truncate the index.txt file.
    ser = figureSerial(ca_cert, serial, index_txt)

    # need to insure the directory declared in the ca_openssl.cnf
    # file is current:
    configFile = ConfigFile(ca_openssl_cnf)
    configFile.updateDir()

    args = ("/usr/bin/openssl ca -extensions req_server_x509_extensions -passin pass:%s -outdir ./ -config %s "
            "-in %s -batch -cert %s -keyfile %s -startdate %s -days %s "
            "-md %s -out %s"
            % ('%s', repr(cleanupAbsPath(ca_openssl_cnf)),
               repr(cleanupAbsPath(server_cert_req)),
               repr(cleanupAbsPath(ca_cert)),
               repr(cleanupAbsPath(ca_key)), d['--startdate'],
               repr(d['--cert-expiration']), MD,
               repr(cleanupAbsPath(server_cert))))

    if verbosity >= 0:
        print("\nGenerating/signing web server's SSL certificate: %s" % d['--server-cert'])
        if verbosity > 1:
            print("Commandline:", args % 'PASSWORD')
    try:
        rotated = rotateFile(filepath=server_cert, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" % (d['--server-cert'],
                                          os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = sstr(out_stream.read()); out_stream.close()
    err = sstr(err_stream.read()); err_stream.close()

    if ret:
        # signature for a mistyped CA password
        if err.find("unable to load CA private key") != -1 \
          and err.find("error:0906A065:PEM routines:PEM_do_header:bad decrypt:pem_lib.c") != -1 \
          and err.find("error:06065064:digital envelope routines:EVP_DecryptFinal:bad decrypt:evp_enc.c") != -1:
            raise GenServerCertException(
                    "web server's SSL certificate generation/signing "
                    "failed:\nDid you mistype your CA password?")
        else:
            raise GenServerCertException(
                    "web server's SSL certificate generation/signing "
                    "failed:\n%s\n%s" % (out, err))

    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(server_cert, int('0644',8))

    # cleanup duplicate XX.pem file:
    pemFilename = os.path.basename(ser.upper()+'.pem')
    if pemFilename != server_cert and os.path.exists(pemFilename):
        os.unlink(pemFilename)

    # cleanup the old index.txt file
    try:
        os.unlink(index_txt + '.old')
    except:
        pass

    # cleanup the old serial file
    try:
        os.unlink(serial + '.old')
#.........这里部分代码省略.........
开发者ID:mcalmer,项目名称:spacewalk,代码行数:101,代码来源:rhn_ssl_tool.py


示例15: genServerCertReq

def genServerCertReq(d, verbosity=0):
    """ private server cert request generation """

    serverKeyPairDir = os.path.join(d['--dir'],
                                    getMachineName(d['--set-hostname']))
    server_key = os.path.join(serverKeyPairDir,
                              os.path.basename(d['--server-key']))
    server_cert_req = os.path.join(serverKeyPairDir,
                                   os.path.basename(d['--server-cert-req']))
    server_openssl_cnf = os.path.join(serverKeyPairDir,
                                      SERVER_OPENSSL_CNF_NAME)

    genServerCertReq_dependencies(d)

    # XXX: hmm.. should private_key, etc. be set for this before the write?
    #      either that you pull the key/certs from the files all together?
    configFile = ConfigFile(server_openssl_cnf)
    if '--set-common-name' in d:
        del d['--set-common-name']
    configFile.save(d, caYN=0, verbosity=verbosity)

    ## generate the server cert request
    args = ("/usr/bin/openssl req -%s -text -config %s -new -key %s -out %s "
            % (MD, repr(cleanupAbsPath(configFile.filename)),
               repr(cleanupAbsPath(server_key)),
               repr(cleanupAbsPath(server_cert_req))))

    if verbosity >= 0:
        print("\nGenerating web server's SSL certificate request: %s" % server_cert_req)
        print("Using distinguished names:")
        for k in ('--set-country', '--set-state', '--set-city', '--set-org',
                  '--set-org-unit', '--set-hostname', '--set-email'):
            print('    %s%s = "%s"' % (k, ' '*(18-len(k)), d[k]))
        if verbosity > 1:
            print("Commandline:", args)

    try:
        rotated = rotateFile(filepath=server_cert_req, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" % (d['--server-cert-req'],
                                          os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenServerCertReqException(
                "web server's SSL certificate request generation "
                "failed:\n%s\n%s" % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # permissions:
    os.chmod(server_cert_req, int('0600',8))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:64,代码来源:rhn_ssl_tool.py


示例16: generateBootstrapScript

def generateBootstrapScript(options):
    "write, copy and place files into /var/www/html/pub/bootstrap/"

    orgCACert = os.path.basename(options.ssl_cert or '')

    # write to /var/www/html/pub/bootstrap/<options.overrides>
    writeClientConfigOverrides(options)

    isRpmYN = processCACertPath(options)
    pubname = os.path.basename(options.pub_tree)

    # generate script
    # In processCommandline() we have turned all boolean values to 0 or 1
    # this means that we can negate those booleans with 1 - their current
    # value (instead of doing not value which can yield True/False, which
    # would print as such)
    newScript = getHeader(PRODUCT_NAME, options.activation_keys,
                  options.gpg_key, options.overrides, options.hostname,
                  orgCACert, isRpmYN, 1 - options.no_ssl, 1 - options.no_gpg,
                  options.allow_config_actions, options.allow_remote_commands,
                  1 - options.no_up2date, pubname)

    writeYN = 1

    # concat all those script-bits
    newScript = newScript + getConfigFilesSh() + getUp2dateScriptsSh()

    
    newScript = newScript + getGPGKeyImportSh() + getCorpCACertSh() + \
                getRegistrationSh(PRODUCT_NAME) 

    #5/16/05 wregglej 159437 - moving stuff that messes with the allowed-action dir to after registration
    if options.allow_config_actions:
        newScript = newScript + getAllowConfigManagement()
    if options.allow_remote_commands:
        newScript = newScript + getAllowRemoteCommands()

    #5/16/05 wregglej 159437 - moved the stuff that up2dates the entire box to after allowed-actions permissions are set.
    newScript = newScript + getUp2dateTheBoxSh()

    _bootstrapDir = cleanupAbsPath(os.path.join(options.pub_tree, 'bootstrap'))
    _script = cleanupAbsPath(os.path.join(_bootstrapDir, options.script))

    if os.path.exists(_script):
        oldScript = open(_script, 'rb').read()
        if oldScript == newScript:
            writeYN = 0
        elif os.path.exists(_script):
            backup = rotateFile(_script, depth=5, verbosity=options.verbose)
            if backup and options.verbose>=0:
                print "* rotating %s --> %s" % (_script, backup)
        del oldScript

    if writeYN:
        fout = open(_script, 'wb')
        fout.write(newScript)
        fout.close()
        print """\
* bootstrap script (written):
    '%s'\n""" % _script
    else:
        print """\
* boostrap script (old and new scripts identical; not written):
    '%s'\n""" % _script
开发者ID:pombredanne,项目名称:spacewalk-1,代码行数:64,代码来源:rhn_bootstrap.py


示例17: genPublicCaCert

def genPublicCaCert(password, d, verbosity=0, forceYN=0):
    """ public CA certificate (client-side) generation """

    ca_key = os.path.join(d['--dir'], os.path.basename(d['--ca-key']))
    ca_cert_name = os.path.basename(d['--ca-cert'])
    ca_cert = os.path.join(d['--dir'], ca_cert_name)
    ca_openssl_cnf = os.path.join(d['--dir'], CA_OPENSSL_CNF_NAME)

    genPublicCaCert_dependencies(password, d, forceYN)

    configFile = ConfigFile(ca_openssl_cnf)
    if '--set-hostname' in d:
        del d['--set-hostname']
    configFile.save(d, caYN=1, verbosity=verbosity)

    args = ("/usr/bin/openssl req -passin pass:%s -text -config %s "
            "-new -x509 -days %s -%s -key %s -out %s"
            % ('%s', repr(cleanupAbsPath(configFile.filename)),
               repr(d['--cert-expiration']),
               MD, repr(cleanupAbsPath(ca_key)),
               repr(cleanupAbsPath(ca_cert))))

    if verbosity >= 0:
        print("\nGenerating public CA certificate: %s" % ca_cert)
        print("Using distinguishing variables:")
        for k in ('--set-country', '--set-state', '--set-city', '--set-org',
                  '--set-org-unit', '--set-common-name', '--set-email'):
            print('    %s%s = "%s"' % (k, ' '*(18-len(k)), d[k]))
        if verbosity > 1:
            print("Commandline:", args % "PASSWORD")

    try:
        rotated = rotateFile(filepath=ca_cert, verbosity=verbosity)
        if verbosity>=0 and rotated:
            print("Rotated: %s --> %s" \
                  % (d['--ca-cert'], os.path.basename(rotated)))
    except ValueError:
        pass

    cwd = chdir(_getWorkDir())
    try:
        ret, out_stream, err_stream = rhn_popen(args % repr(password))
    finally:
        chdir(cwd)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenPublicCaCertException("Certificate Authority public "
                                   "SSL certificate generation failed:\n%s\n"
                                   "%s" % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    latest_txt = os.path.join(d['--dir'], 'latest.txt')
    fo = open(latest_txt, 'wb')
    fo.write(bstr('%s\n' % ca_cert_name))
    fo.close()

    # permissions:
    os.chmod(ca_cert, int('0644',8))
    os.chmod(latest_txt, int('0644',8))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:65,代码来源:rhn_ssl_tool.py



注:本文中的spacewalk.common.fileutils.rotateFile函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python rhnCache.get函数代码示例发布时间:2022-05-27
下一篇:
Python fileutils.rhn_popen函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap