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

Python fileutils.rhn_popen函数代码示例

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

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



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

示例1: enableSatelliteRepo

def enableSatelliteRepo(rhn_cert):
    args = ['rpm', '-q', '--qf', '\'%{version}\'', '-f', '/etc/redhat-release']
    ret, out, err = fileutils.rhn_popen(args)
    # Read from stdout, strip quotes if any and extract first number
    version = re.search(r'\d+', out.read().strip("'")).group()

    if version not in SUPPORTED_RHEL_VERSIONS:
        msg = "WARNING: No Satellite repository available for RHEL version: %s.\n" % version
        sys.stderr.write(msg)
        return

    sat_cert = satellite_cert.SatelliteCert()
    sat_cert.load(rhn_cert)
    sat_version = getattr(sat_cert, 'satellite-version')

    repo = "rhel-%s-server-satellite-%s-rpms" % (version, sat_version)
    args = ['/usr/bin/subscription-manager', 'repos', '--enable', repo]
    ret, out, err = fileutils.rhn_popen(args)
    if ret:
        msg_ = "Enabling of Satellite repository failed."
        msg = ("%s\nReturn value: %s\nStandard-out: %s\n\n"
               "Standard-error: %s\n\n"
               % (msg_, ret, out.read(), err.read()))
        sys.stderr.write(msg)
        raise EnableSatelliteRepositoryException("Enabling of Satellite repository failed. Is there Satellite "
                                                 "subscription attached to this system? Is the version of "
                                                 "RHEL and Satellite certificate correct?")
开发者ID:phurrelmann,项目名称:spacewalk,代码行数:27,代码来源:rhn_satellite_activate.py


示例2: enableSatelliteRepo

def enableSatelliteRepo(rhn_cert):
    args = ['rpm', '-q', '--qf', '\'%{version} %{arch}\'', '-f', '/etc/redhat-release']
    ret, out, err = fileutils.rhn_popen(args)
    data = out.read().strip("'")
    version, arch = data.split()
    # Read from stdout, strip quotes if any and extract first number
    version = re.search(r'\d+', version).group()

    if version not in SUPPORTED_RHEL_VERSIONS:
        log(0, "WARNING: No Satellite repository available for RHEL version: %s." % version)
        return

    arch_str = "server"
    if arch == "s390x":
        arch_str = "system-z"

    sat_cert = satellite_cert.SatelliteCert()
    sat_cert.load(rhn_cert)
    sat_version = getattr(sat_cert, 'satellite-version')

    repo = "rhel-%s-%s-satellite-%s-rpms" % (version, arch_str, sat_version)
    args = ['/usr/bin/subscription-manager', 'repos', '--enable', repo]
    ret, out, err = fileutils.rhn_popen(args)
    if ret:
        msg_ = "Enabling of Satellite repository failed."
        msg = ("%s\nReturn value: %s\nStandard-out: %s\n\n"
               "Standard-error: %s\n"
               % (msg_, ret, out.read(), err.read()))
        writeError(msg)
        raise EnableSatelliteRepositoryException("Enabling of Satellite repository failed. Make sure Satellite "
                                                 "subscription is attached to this system, both versions of RHEL and "
                                                 "Satellite are supported or run activation with --disconnected "
                                                 "option.")
开发者ID:lhellebr,项目名称:spacewalk,代码行数:33,代码来源:rhn_satellite_activate.py


示例3: verify_mappings

def verify_mappings():
    args = ['rpm', '-q', constants.MAPPINGS_RPM_NAME]
    ret = fileutils.rhn_popen(args)
    # Package installed, exitcode is 0
    if not ret[0]:
        args = ['rpm', '-V', constants.MAPPINGS_RPM_NAME]
        ret = fileutils.rhn_popen(args)
        if ret[0]:
            raise CdnMappingsLoadError("CDN mappings changed on disk. Please re-install '%s' package."
                                       % constants.MAPPINGS_RPM_NAME)
开发者ID:jdobes,项目名称:spacewalk,代码行数:10,代码来源:common.py


示例4: validateSatCert

def validateSatCert(certFilename, verbosity=0):
    """ validating (i.e., verifing sanity of) this product. Calls
        validate-sat-cert.pl
        I.e., makes sure the product Certificate is a sane certificate
    """

    # copy cert to temp location (it may be gzipped which validate-sat-cert.pl
    # doesn't like).
    fd, certTmpFile = tempfile.mkstemp(prefix=DEFAULT_RHN_CERT_LOCATION + "-")
    fo = os.fdopen(fd, "wb")
    fo.write(string.strip(openGzippedFile(certFilename).read()))
    fo.flush()
    fo.close()

    args = ["/usr/bin/validate-sat-cert.pl", "--keyring", DEFAULT_WEBAPP_GPG_KEY_RING, certTmpFile]

    if verbosity:
        print "Checking cert XML sanity and GPG signature:", repr(string.join(args))

    ret, out, err = fileutils.rhn_popen(args)
    err = err.read()
    out = out.read()

    # nuke temp cert
    os.unlink(certTmpFile)

    if string.find(err, "verify err") != -1 or ret:
        msg = "%s Entitlement Certificate failed to validate.\n" % PRODUCT_NAME
        msg = msg + "MORE INFORMATION:\n"
        msg = msg + "  Return value: %s\n" % ret + "  Standard-out: %s\n" % out + "  Standard-error: %s\n" % err
        sys.stderr.write(msg)
        raise RHNCertGeneralSanityException("RHN Entitlement Certificate failed " "to validate.")
    return 0
开发者ID:pombredanne,项目名称:spacewalk-1,代码行数:33,代码来源:rhn_satellite_activate.py


示例5: figureSerial

def figureSerial(caCertFilename, serialFilename, indexFilename):
    """ for our purposes we allow the same serial number for server certs
        BUT WE DO NOT ALLOW server certs and CA certs to share the same
        serial number.

        We blow away the index.txt file each time because we are less
        concerned with matching serials/signatures between server.crt's.
    """

    # what serial # is the ca cert using (we need to increment from that)
    ret, outstream, errstream = rhn_popen(['/usr/bin/openssl', 'x509', '-noout',
                                           '-serial', '-in', caCertFilename])
    out = outstream.read()
    outstream.close()
    errstream.read()
    errstream.close()
    assert not ret
    caSerial = string.split(string.strip(out), '=')
    assert len(caSerial) > 1
    caSerial = caSerial[1]
    caSerial = eval('0x'+caSerial)

    # initialize the serial value (starting at whatever is in
    # serialFilename or 1)
    serial = 1
    if os.path.exists(serialFilename):
        serial = string.strip(open(serialFilename, 'r').read())
        if serial:
            serial = eval('0x'+serial)
        else:
            serial = 1

    # make sure it is at least 1 more than the CA's serial code always
    # REMEMBER: openssl will incremented the serial number each time
    # as well.
    if serial <= caSerial:
        serial = incSerial(hex(caSerial))
        serial = eval('0x' + serial)
    serial = fixSerial(hex(serial))

    # create the serial file if it doesn't exist
    # write the digits to this file
    open(serialFilename, 'w').write(serial+'\n')
    os.chmod(serialFilename, 0600)

    # truncate the index.txt file. Less likely to have unneccessary clashes.
    open(indexFilename, 'w')
    os.chmod(indexFilename, 0600)
    return serial
开发者ID:NehaRawat,项目名称:spacewalk,代码行数:49,代码来源: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: populateChannelFamilies

def populateChannelFamilies(options):
    """ Populate channel family permissions via satellite-sync """

    # TODO: Can't we do this programatically?
    args = ["/usr/bin/satellite-sync", "--list-channels"]

    # The next three if-blocks remove dependence on /etc/rhn/rhn.conf being
    # written (not a large gain, but there it is).
    # use a http proxy with satellite-sync
    if options.http_proxy:
        args.extend(["--http-proxy", options.http_proxy])
        if options.http_proxy_username:
            args.extend(["--http-proxy-username", options.http_proxy_username])
            if options.http_proxy_password:
                args.extend(["--http-proxy-password", options.http_proxy_password])

    # use a ca cert with satellite-sync
    if options.ca_cert:
        args.extend(["--ca-cert", options.ca_cert])

    # use a ca cert with satellite-sync
    if options.no_ssl:
        args.extend(["--no-ssl"])

    if options.dump_version:
        args.extend(["--dump-version", options.dump_version])

    ## database string for that satellite-sync
    # if options.db:
    #    args.extend(['--db', options.db])

    if options.verbose:
        print "Executing: %s\n" % repr(string.join(args))
    ret, out_stream, err_stream = fileutils.rhn_popen(args)
    if ret:
        msg_ = "Population of the Channel Family permissions failed."
        msg = "%s\nReturn value: %s\nStandard-out: %s\n\n" "Standard-error: %s\n\n" % (
            msg_,
            ret,
            out_stream.read(),
            err_stream.read(),
        )
        sys.stderr.write(msg)
        raise PopulateChannelFamiliesException("Population of the Channel " "Family permissions failed.")
开发者ID:pombredanne,项目名称:spacewalk-1,代码行数:44,代码来源:rhn_satellite_activate.py


示例9: checkCaCert

def checkCaCert(d, verbosity=0):
    """ check CA key's password """

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

    args = ("/usr/bin/openssl x509 -in %s -noout"
            % (repr(cleanupAbsPath(cleanupAbsPath(ca_cert)))))

    if verbosity >= 0:
        print("\nChecking CA cert's validity: %s" % ca_cert)
    if verbosity > 1:
        print("Commandline:", args)

    ret, out_stream, err_stream = rhn_popen(args)

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenPrivateCaKeyException("Certificate Authority certificate "
                                   "does not exist or is broken:\n%s\n"
                                   "%s" % (out, err))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:21,代码来源:rhn_ssl_tool.py


示例10: checkCaKey

def checkCaKey(password, d, verbosity=0):
    """ check CA key's password """

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

    args = ("/usr/bin/openssl rsa -in %s -check -passin pass:%s"
            % (repr(cleanupAbsPath(cleanupAbsPath(ca_key))), "%s"))

    if verbosity >= 0:
        print("\nChecking private CA key's password: %s" % ca_key)
    if verbosity > 1:
        print("Commandline:", args % "PASSWORD")

    ret, out_stream, err_stream = rhn_popen(args % repr(password))

    out = out_stream.read(); out_stream.close()
    err = err_stream.read(); err_stream.close()
    if ret:
        raise GenPrivateCaKeyException("Certificate Authority private "
                                   "key's password does not match or "
                                   "key broken:\n%s\n"
                                   "%s" % (out, err))
开发者ID:mcalmer,项目名称:spacewalk,代码行数:22,代码来源:rhn_ssl_tool.py


示例11: getCertValidityRange

def getCertValidityRange(certPath, daysYN=0):
    """ parse a cert (x509) and snag the validity range.
        Returns (notBefore, notAfter) in seconds or days the epoch.
    """
    certPath = cleanupAbsPath(certPath)
    if not os.path.exists(certPath):
        return None, None

    args = "/usr/bin/openssl x509 -dates -noout -in %s" % certPath
    ret, out_stream, err_stream = rhn_popen(args)

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

    out = string.strip(out)

    if ret or not out:
        raise RhnSslToolException("certificate parse (for validity range) "
                                  "failed:\n%s\n%s" % (out, err))

    if out \
      and string.find(out, 'notBefore=')!=-1 \
      and string.find(out, 'notAfter=')!=-1:
        notBefore, notAfter = string.split(out, '\n')
        notBefore = string.strip(string.split(notBefore, 'notBefore=')[1])[:-4]
        notAfter = string.strip(string.split(notAfter, 'notAfter=')[1])[:-4]
        # secs from epoch
        notBefore = str2secs(notBefore, '%b %d %H:%M:%S %Y')
        notAfter = str2secs(notAfter, '%b %d %H:%M:%S %Y')
        if daysYN:
            # days from epoch
            notBefore = secs2days(notBefore)
            notAfter = secs2days(notAfter)
        return notBefore, notAfter
    else:
        raise RhnSslToolException("certificate parse (for validity range) "
                                  "failed:\n%s\n%s" % (out, err))
开发者ID:pombredanne,项目名称:spacewalk-1,代码行数:37,代码来源:sslToolLib.py


示例12: 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


示例13: genServerRpm


#.........这里部分代码省略.........
""" % d['--set-hostname']

    # Determine which jabberd user exists:
    jabberd_user = None
    possible_jabberd_users = ['jabberd', 'jabber']
    for juser_attempt in possible_jabberd_users:
        try:
            pwd.getpwnam(juser_attempt)
            jabberd_user = juser_attempt
        except:
            # user doesn't exist, try the next
            pass
    if jabberd_user is None:
        print("WARNING: No jabber/jabberd user on system, skipping " +
                "jabberd.pem generation.")

    jabberd_cert_string = ""
    if jabberd_user is not None:
        jabberd_cert_string = \
            "/etc/pki/spacewalk/jabberd/server.pem:0600,%s,%s=%s" % \
            (jabberd_user, jabberd_user, repr(cleanupAbsPath(jabberd_ssl_cert)))


    ## build the server RPM
    args = (os.path.join(CERT_PATH, 'gen-rpm.sh') + " "
            "--name %s --version %s --release %s --packager %s --vendor %s "
            "--group 'RHN/Security' --summary %s --description %s --postun %s "
            "/etc/httpd/conf/ssl.key/server.key:0600=%s "
            "/etc/httpd/conf/ssl.csr/server.csr=%s "
            "/etc/httpd/conf/ssl.crt/server.crt=%s "
            "%s"
            % (repr(server_rpm_name), ver, rel, repr(d['--rpm-packager']),
               repr(d['--rpm-vendor']),
               repr(SERVER_RPM_SUMMARY), repr(description),
               repr(cleanupAbsPath(postun_scriptlet)),
               repr(cleanupAbsPath(server_key)),
               repr(cleanupAbsPath(server_cert_req)),
               repr(cleanupAbsPath(server_cert)),
               jabberd_cert_string
               ))
    serverRpmName = "%s-%s-%s" % (server_rpm, ver, rel)

    if verbosity >= 0:
        print("""
Generating web server's SSL key pair/set RPM:
    %s.src.rpm
    %s.noarch.rpm""" % (serverRpmName, serverRpmName))
        if verbosity > 1:
            print("Commandline:", args)

    if verbosity >= 4:
        print('Current working directory:', os.getcwd())
        print("Writing postun_scriptlet:", postun_scriptlet)
    open(postun_scriptlet, 'w').write(POST_UNINSTALL_SCRIPT)

    _disableRpmMacros()
    cwd = chdir(serverKeyPairDir)
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    finally:
        chdir(cwd)
        _reenableRpmMacros()
        os.unlink(postun_scriptlet)

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

    if ret or not os.path.exists("%s.noarch.rpm" % serverRpmName):
        raise GenServerRpmException("web server's SSL key set RPM generation "
                                    "failed:\n%s\n%s" % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    os.chmod('%s.noarch.rpm' % serverRpmName, int('0600',8))

    # generic the tarball necessary for Spacewalk Proxy against hosted installations
    tarballFilepath = genProxyServerTarball(d, version=ver, release=rel,
                                            verbosity=verbosity)

    # write-out latest.txt information
    latest_txt = os.path.join(serverKeyPairDir, 'latest.txt')
    fo = open(latest_txt, 'wb')
    fo.write(bstr('%s.noarch.rpm\n' % os.path.basename(serverRpmName)))
    fo.write(bstr('%s.src.rpm\n' % os.path.basename(serverRpmName)))
    fo.write(bstr('%s\n' % os.path.basename(tarballFilepath)))
    fo.close()
    os.chmod(latest_txt, int('0600',8))

    if verbosity >= 0:
        print("""
Deploy the server's SSL key pair/set RPM:
    (NOTE: the Red Hat Satellite or Proxy installers may do this step for you.)
    The "noarch" RPM needs to be deployed to the machine working as a
    web server, or Red Hat Satellite, or Spacewalk Proxy.
    Presumably %s.""" % repr(d['--set-hostname']))

    return "%s.noarch.rpm" % serverRpmName
开发者ID:mcalmer,项目名称:spacewalk,代码行数:101,代码来源:rhn_ssl_tool.py


示例14: genProxyServerTarball

def genProxyServerTarball(d, version='1.0', release='1', verbosity=0):
    """ generates the Spacewalk Proxy Server's tar archive containing its
        SSL key set + CA certificate
    """

    genProxyServerTarball_dependencies(d)

    tarballFilepath = getTarballFilename(d, version, release)[1]
    tarballFilepath = pathJoin(d['--dir'], tarballFilepath)

    machinename = getMachineName(d['--set-hostname'])
    ca_cert = os.path.basename(d['--ca-cert'])
    server_key = pathJoin(machinename, d['--server-key'])
    server_cert = pathJoin(machinename, d['--server-cert'])
    server_cert_req = pathJoin(machinename, d['--server-cert-req'])
    jabberd_ssl_cert = os.path.join(machinename, d['--jabberd-ssl-cert'])

    ## build the server tarball
    args = '/bin/tar -cvf %s %s %s %s %s %s' \
           % (repr(os.path.basename(tarballFilepath)), repr(ca_cert),
              repr(server_key), repr(server_cert), repr(server_cert_req),
              repr(jabberd_ssl_cert))

    serverKeySetDir = pathJoin(d['--dir'], machinename)
    tarballFilepath2 = pathJoin(serverKeySetDir, tarballFilepath)

    if verbosity >= 0:
        print("""
The most current Spacewalk Proxy Server installation process against RHN hosted
requires the upload of an SSL tar archive that contains the CA SSL public
certificate and the web server's key set.

Generating the web server's SSL key set and CA SSL public certificate archive:
    %s""" % tarballFilepath2)

    cwd = chdir(d['--dir'])
    try:
        if verbosity > 1:
            print("Current working directory:", os.getcwd())
            print("Commandline:", args)
        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 or not os.path.exists(tarballFilepath):
        raise GenServerTarException(
          "CA SSL public certificate & web server's SSL key set tar archive\n"
          "generation failed:\n%s\n%s" % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)

    # root baby!
    os.chmod(tarballFilepath, int('0600',8))

    # copy tarball into machine build dir
    shutil.copy2(tarballFilepath, tarballFilepath2)
    os.unlink(tarballFilepath)
    if verbosity > 1:
        print("""\
Moved to final home:
    %s
    ...moved to...
    %s""" % (tarballFilepath, tarballFilepath2))

    return tarballFilepath2
开发者ID:mcalmer,项目名称:spacewalk,代码行数:71,代码来源:rhn_ssl_tool.py


示例15: genCaRpm

def genCaRpm(d, verbosity=0):
    """ generates ssl cert RPM. """

    ca_cert_name = os.path.basename(d['--ca-cert'])
    ca_cert = os.path.join(d['--dir'], ca_cert_name)
    ca_cert_rpm_name = os.path.basename(d['--ca-cert-rpm'])
    ca_cert_rpm = os.path.join(d['--dir'], ca_cert_rpm_name)

    genCaRpm_dependencies(d)

    if verbosity>=0:
        sys.stderr.write("\n...working...")
    # Work out the release number.
    hdr = getInstalledHeader(ca_cert_rpm)

    #find RPMs in the directory
    filenames = glob.glob("%s-*.noarch.rpm" % ca_cert_rpm)
    if filenames:
        filename = sortRPMs(filenames)[-1]
        h = get_package_header(filename)
        if hdr is None:
            hdr = h
        else:
            comp = hdrLabelCompare(h, hdr)
            if comp > 0:
                hdr = h

    epo, ver, rel = None, '1.0', '0'
    if hdr is not None:
        epo, ver, rel = hdr['epoch'], hdr['version'], hdr['release']

    # bump the release - and let's not be too smart about it
    #                    assume the release is a number.
    if rel:
        rel = str(int(rel)+1)

    update_trust_script = os.path.join(CERT_PATH, 'update-ca-cert-trust.sh')

    # build the CA certificate RPM
    args = (os.path.join(CERT_PATH, 'gen-rpm.sh') + " "
            "--name %s --version %s --release %s --packager %s --vendor %s "
            "--group 'RHN/Security' --summary %s --description %s "
            "--post %s --postun %s "
            "/usr/share/rhn/%s=%s"
            % (repr(ca_cert_rpm_name), ver, rel, repr(d['--rpm-packager']),
               repr(d['--rpm-vendor']), repr(CA_CERT_RPM_SUMMARY),
               repr(CA_CERT_RPM_SUMMARY),
               repr(update_trust_script), repr(update_trust_script),
               repr(ca_cert_name), repr(cleanupAbsPath(ca_cert))))
    clientRpmName = '%s-%s-%s' % (ca_cert_rpm, ver, rel)
    if verbosity >= 0:
        print("""
Generating CA public certificate RPM:
    %s.src.rpm
    %s.noarch.rpm""" % (clientRpmName, clientRpmName))
        if verbosity > 1:
            print("Commandline:", args)

    _disableRpmMacros()
    cwd = chdir(d['--dir'])
    try:
        ret, out_stream, err_stream = rhn_popen(args)
    except Exception:
        chdir(cwd)
        _reenableRpmMacros()
        raise
    chdir(cwd)
    _reenableRpmMacros()

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

    if ret or not os.path.exists("%s.noarch.rpm" % clientRpmName):
        raise GenCaCertRpmException("CA public SSL certificate RPM generation "
                                "failed:\n%s\n%s" % (out, err))
    if verbosity > 2:
        if out:
            print("STDOUT:", out)
        if err:
            print("STDERR:", err)
    os.chmod('%s.noarch.rpm' % clientRpmName, int('0644',8))

    # write-out latest.txt information
    latest_txt = os.path.join(d['--dir'], 'latest.txt')
    fo = open(latest_txt, 'wb')
    fo.write(bstr('%s\n' % ca_cert_name))
    fo.write(bstr('%s.noarch.rpm\n' % os.path.basename(clientRpmName)))
    fo.write(bstr('%s.src.rpm\n' % os.path.basename(clientRpmName)))
    fo.close()
    os.chmod(latest_txt, int('0644',8))

    if verbosity >= 0:
        print("""
Make the public CA certficate publically available:
    (NOTE: the Red Hat Satellite or Proxy installers may do this step for you.)
    The "noarch" RPM and raw CA certificate can be made publically accessible
    by copying it to the /var/www/html/pub directory of your Red Hat Satellite or
    Proxy server.""")


#.........这里部分代码省略.........
开发者ID:mcalmer,项目名称:spacewalk,代码行数:101,代码来源:rhn_ssl_tool.py


示例16: 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


示例17: 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



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Python fileutils.rotateFile函数代码示例发布时间:2022-05-27
下一篇:
Python fileutils.createPath函数代码示例发布时间: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