当前位置: 首页>>代码示例>>Python>>正文


Python Utils.Executor类代码示例

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


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

示例1: create_key

 def create_key(self):
     """Creates a bcfg2.key at the directory specifed by keypath."""
     cmd = Executor(timeout=120)
     subject = "/C=%s/ST=%s/L=%s/CN=%s'" % (
         self.data['country'], self.data['state'], self.data['location'],
         self.data['shostname'])
     key = cmd.run(["openssl", "req", "-batch", "-x509", "-nodes",
                    "-subj", subject, "-days", "1000",
                    "-newkey", "rsa:2048",
                    "-keyout", self.data['keypath'], "-noout"])
     if not key.success:
         print("Error generating key: %s" % key.error)
         return
     os.chmod(self.data['keypath'], stat.S_IRUSR | stat.S_IWUSR)  # 0600
     csr = cmd.run(["openssl", "req", "-batch", "-new", "-subj", subject,
                    "-key", self.data['keypath']])
     if not csr.success:
         print("Error generating certificate signing request: %s" %
               csr.error)
         return
     cert = cmd.run(["openssl", "x509", "-req", "-days", "1000",
                     "-signkey", self.data['keypath'],
                     "-out", self.data['certpath']],
                    inputdata=csr.stdout)
     if not cert.success:
         print("Error signing certificate: %s" % cert.error)
         return
开发者ID:feuri,项目名称:bcfg2,代码行数:27,代码来源:Admin.py

示例2: Fossil

class Fossil(Bcfg2.Server.Plugin.Version):
    """ The Fossil plugin provides a revision interface for Bcfg2
    repos using fossil. """
    __author__ = '[email protected]'
    __vcs_metadata_path__ = "_FOSSIL_"

    def __init__(self, core):
        Bcfg2.Server.Plugin.Version.__init__(self, core)
        self.cmd = Executor()
        self.logger.debug("Initialized Fossil plugin with fossil directory %s"
                          % self.vcs_path)

    def get_revision(self):
        """Read fossil revision information for the Bcfg2 repository."""
        result = self.cmd.run(["env LC_ALL=C", "fossil", "info"],
                              shell=True, cwd=Bcfg2.Options.setup.vcs_root)
        try:
            revision = None
            for line in result.stdout.splitlines():
                ldata = line.split(': ')
                if ldata[0].strip() == 'checkout':
                    revision = line[1].strip().split(' ')[0]
            return revision
        except (IndexError, AttributeError):
            msg = "Failed to read revision from Fossil: %s" % result.error
            self.logger.error(msg)
            raise Bcfg2.Server.Plugin.PluginExecutionError(msg)
开发者ID:AlexanderS,项目名称:bcfg2,代码行数:27,代码来源:Fossil.py

示例3: __init__

 def __init__(self, core):
     Bcfg2.Server.Plugin.Plugin.__init__(self, core)
     Bcfg2.Server.Plugin.Connector.__init__(self)
     Bcfg2.Server.Plugin.ClientRunHooks.__init__(self)
     Bcfg2.Server.Plugin.DirectoryBacked.__init__(self, self.data)
     self.cache = dict()
     self.cmd = Executor()
开发者ID:AlexanderS,项目名称:bcfg2,代码行数:7,代码来源:PuppetENC.py

示例4: __init__

    def __init__(self, core, datastore):
        Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)
        Bcfg2.Server.Plugin.Generator.__init__(self)
        Bcfg2.Server.Plugin.PullTarget.__init__(self)
        self.ipcache = {}
        self.namecache = {}
        self.__skn = False

        # keep track of which bogus keys we've warned about, and only
        # do so once
        self.badnames = dict()

        self.fam = Bcfg2.Server.FileMonitor.get_fam()
        self.fam.AddMonitor(self.data, self)

        self.static = dict()
        self.entries = dict()
        self.Entries["Path"] = dict()

        self.entries["/etc/ssh/ssh_known_hosts"] = KnownHostsEntrySet(self.data)
        self.Entries["Path"]["/etc/ssh/ssh_known_hosts"] = self.build_skn
        for keypattern in self.keypatterns:
            self.entries["/etc/ssh/" + keypattern] = HostKeyEntrySet(keypattern, self.data)
            self.Entries["Path"]["/etc/ssh/" + keypattern] = self.build_hk

        self.cmd = Executor()
开发者ID:shellox,项目名称:bcfg2,代码行数:26,代码来源:SSHbase.py

示例5: __init__

 def __init__(self, _, path, entry_type, parent=None):
     Bcfg2.Server.Plugin.EntrySet.__init__(self, os.path.basename(path),
                                           path, entry_type)
     self.parent = parent
     self.key = None
     self.cert = None
     self.cmd = Executor(timeout=120)
开发者ID:dhutty,项目名称:bcfg2,代码行数:7,代码来源:SSLCA.py

示例6: __init__

    def __init__(self, *args, **kwargs):
        Bcfg2.Server.Lint.ServerlessPlugin.__init__(self, *args, **kwargs)
        self.filesets = \
            {"Metadata/groups.xml": "metadata.xsd",
             "Metadata/clients.xml": "clients.xsd",
             "Cfg/**/info.xml": "info.xsd",
             "Cfg/**/privkey.xml": "privkey.xsd",
             "Cfg/**/pubkey.xml": "pubkey.xsd",
             "Cfg/**/authorizedkeys.xml": "authorizedkeys.xsd",
             "Cfg/**/authorized_keys.xml": "authorizedkeys.xsd",
             "SSHbase/**/info.xml": "info.xsd",
             "SSLCA/**/info.xml": "info.xsd",
             "TGenshi/**/info.xml": "info.xsd",
             "TCheetah/**/info.xml": "info.xsd",
             "Bundler/*.xml": "bundle.xsd",
             "Bundler/*.genshi": "bundle.xsd",
             "Pkgmgr/*.xml": "pkglist.xsd",
             "Rules/*.xml": "rules.xsd",
             "Defaults/*.xml": "defaults.xsd",
             "etc/report-configuration.xml": "report-configuration.xsd",
             "Deps/*.xml": "deps.xsd",
             "Decisions/*.xml": "decisions.xsd",
             "Packages/sources.xml": "packages.xsd",
             "GroupPatterns/config.xml": "grouppatterns.xsd",
             "NagiosGen/config.xml": "nagiosgen.xsd",
             "FileProbes/config.xml": "fileprobes.xsd",
             "SSLCA/**/cert.xml": "sslca-cert.xsd",
             "SSLCA/**/key.xml": "sslca-key.xsd",
             "GroupLogic/groups.xml": "grouplogic.xsd"
             }

        self.filelists = {}
        self.get_filelists()
        self.cmd = Executor()
开发者ID:hughdbrown,项目名称:bcfg2,代码行数:34,代码来源:Validate.py

示例7: __init__

    def __init__(self):
        self.config = None
        self._proxy = None
        self.logger = logging.getLogger('bcfg2')
        self.cmd = Executor(Bcfg2.Options.setup.probe_timeout)
        self.tools = []
        self.times = dict()
        self.times['initialization'] = time.time()

        if Bcfg2.Options.setup.bundle_quick:
            if (not Bcfg2.Options.setup.only_bundles and
                    not Bcfg2.Options.setup.except_bundles):
                self.logger.error("-Q option requires -b or -B")
                raise SystemExit(1)
        if Bcfg2.Options.setup.remove == 'services':
            self.logger.error("Service removal is nonsensical; "
                              "removed services will only be disabled")
        if not Bcfg2.Options.setup.server.startswith('https://'):
            Bcfg2.Options.setup.server = \
                'https://' + Bcfg2.Options.setup.server

        #: A dict of the state of each entry.  Keys are the entries.
        #: Values are boolean: True means that the entry is good,
        #: False means that the entry is bad.
        self.states = {}
        self.whitelist = []
        self.blacklist = []
        self.removal = []
        self.unhandled = []
        self.logger = logging.getLogger(__name__)
开发者ID:Ank2015,项目名称:bcfg2,代码行数:30,代码来源:__init__.py

示例8: __init__

    def __init__(self, core):
        Bcfg2.Server.Plugin.Version.__init__(self, core)

        self.revision = None
        self.svn_root = None
        self.client = None
        self.cmd = None
        if not HAS_SVN:
            self.logger.debug("Svn: PySvn not found, using CLI interface to "
                              "SVN")
            self.cmd = Executor()
        else:
            self.client = pysvn.Client()
            self.debug_log("Svn: Conflicts will be resolved with %s" %
                           Bcfg2.Options.setup.svn_conflict_resolution)
            self.client.callback_conflict_resolver = self.conflict_resolver

            if Bcfg2.Options.setup.svn_trust_ssl:
                self.client.callback_ssl_server_trust_prompt = \
                    self.ssl_server_trust_prompt

            if (Bcfg2.Options.setup.svn_user and
                    Bcfg2.Options.setup.svn_password):
                self.client.callback_get_login = self.get_login

        self.logger.debug("Svn: Initialized svn plugin with SVN directory %s" %
                          self.vcs_path)
开发者ID:fabaff,项目名称:bcfg2,代码行数:27,代码来源:Svn.py

示例9: __init__

    def __init__(self, metadata, sources, cachepath, basepath, debug=False):
        Collection.__init__(self, metadata, sources, cachepath, basepath, debug=debug)
        self.keypath = os.path.join(self.cachepath, "keys")

        self._helper = None
        if self.use_yum:
            #: Define a unique cache file for this collection to use
            #: for cached yum metadata
            self.cachefile = os.path.join(self.cachepath, "cache-%s" % self.cachekey)
            if not os.path.exists(self.cachefile):
                os.mkdir(self.cachefile)

            #: The path to the server-side config file used when
            #: resolving packages with the Python yum libraries
            self.cfgfile = os.path.join(self.cachefile, "yum.conf")
            self.write_config()
            self.cmd = Executor()
        else:
            self.cachefile = None
            self.cmd = None

        if HAS_PULP and self.has_pulp_sources:
            _setup_pulp()
            if self.pulp_cert_set is None:
                certdir = os.path.join(self.basepath, "pulp", os.path.basename(PulpCertificateSet.certpath))
                try:
                    os.makedirs(certdir)
                except OSError:
                    err = sys.exc_info()[1]
                    if err.errno == errno.EEXIST:
                        pass
                    else:
                        self.logger.error("Could not create Pulp consumer " "cert directory at %s: %s" % (certdir, err))
                self.pulp_cert_set = PulpCertificateSet(certdir)
开发者ID:shellox,项目名称:bcfg2,代码行数:34,代码来源:Yum.py

示例10: CfgExternalCommandVerifier

class CfgExternalCommandVerifier(CfgVerifier):
    """ Invoke an external script to verify
    :ref:`server-plugins-generators-cfg` file contents """

    #: Handle :file:`:test` files
    __basenames__ = [':test']

    def __init__(self, name, specific, encoding):
        CfgVerifier.__init__(self, name, specific, encoding)
        self.cmd = []
        self.exc = Executor(timeout=30)
    __init__.__doc__ = CfgVerifier.__init__.__doc__

    def verify_entry(self, entry, metadata, data):
        try:
            result = self.exc.run(self.cmd, inputdata=data)
            if not result.success:
                raise CfgVerificationError(result.error)
        except OSError:
            raise CfgVerificationError(sys.exc_info()[1])
    verify_entry.__doc__ = CfgVerifier.verify_entry.__doc__

    def handle_event(self, event):
        CfgVerifier.handle_event(self, event)
        if not self.data:
            return
        self.cmd = []
        if not os.access(self.name, os.X_OK):
            bangpath = self.data.splitlines()[0].strip()
            if bangpath.startswith("#!"):
                self.cmd.extend(shlex.split(bangpath[2:].strip()))
            else:
                raise PluginExecutionError("Cannot execute %s" % self.name)
        self.cmd.append(self.name)
    handle_event.__doc__ = CfgVerifier.handle_event.__doc__
开发者ID:danfoster,项目名称:bcfg2,代码行数:35,代码来源:CfgExternalCommandVerifier.py

示例11: __init__

    def __init__(self, fname):
        CfgCreator.__init__(self, fname)
        StructFile.__init__(self, fname)

        pubkey_path = os.path.dirname(self.name) + ".pub"
        pubkey_name = os.path.join(pubkey_path, os.path.basename(pubkey_path))
        self.pubkey_creator = CfgPublicKeyCreator(pubkey_name)
        self.cmd = Executor()
开发者ID:dhutty,项目名称:bcfg2,代码行数:8,代码来源:CfgPrivateKeyCreator.py

示例12: __init__

    def __init__(self, core, datastore):
        Bcfg2.Server.Plugin.Version.__init__(self, core, datastore)

        self.revision = None
        self.svn_root = None
        self.client = None
        self.cmd = None
        if not HAS_SVN:
            self.logger.debug("Svn: PySvn not found, using CLI interface to "
                              "SVN")
            self.cmd = Executor()
        else:
            self.client = pysvn.Client()
            # pylint: disable=E1101
            choice = pysvn.wc_conflict_choice.postpone
            try:
                resolution = self.core.setup.cfp.get(
                    "svn",
                    "conflict_resolution").replace('-', '_')
                if resolution in ["edit", "launch", "working"]:
                    self.logger.warning("Svn: Conflict resolver %s requires "
                                        "manual intervention, using %s" %
                                        choice)
                else:
                    choice = getattr(pysvn.wc_conflict_choice, resolution)
            except AttributeError:
                self.logger.warning("Svn: Conflict resolver %s does not "
                                    "exist, using %s" % choice)
            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                self.logger.info("Svn: No conflict resolution method "
                                 "selected, using %s" % choice)
            # pylint: enable=E1101
            self.debug_log("Svn: Conflicts will be resolved with %s" %
                           choice)
            self.client.callback_conflict_resolver = \
                self.get_conflict_resolver(choice)

            try:
                if self.core.setup.cfp.get(
                        "svn",
                        "always_trust").lower() == "true":
                    self.client.callback_ssl_server_trust_prompt = \
                        self.ssl_server_trust_prompt
            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                self.logger.debug("Svn: Using subversion cache for SSL "
                                  "certificate trust")

            try:
                if (self.core.setup.cfp.get("svn", "user") and
                    self.core.setup.cfp.get("svn", "password")):
                    self.client.callback_get_login = \
                        self.get_login
            except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
                self.logger.info("Svn: Using subversion cache for "
                                 "password-based authetication")

        self.logger.debug("Svn: Initialized svn plugin with SVN directory %s" %
                          self.vcs_path)
开发者ID:igorwidlinski,项目名称:bcfg2,代码行数:58,代码来源:Svn.py

示例13: run

    def run(self, setup):
        if setup.outfile:
            fmt = setup.outfile.split('.')[-1]
        else:
            fmt = 'png'

        exc = Executor()
        cmd = ["dot", "-T", fmt]
        if setup.outfile:
            cmd.extend(["-o", setup.outfile])
        inputlist = ["digraph groups {",
                     '\trankdir="LR";',
                     self.metadata.viz(setup.includehosts,
                                       setup.includebundles,
                                       setup.includekey,
                                       setup.only_client,
                                       self.colors)]
        if setup.includekey:
            inputlist.extend(
                ["\tsubgraph cluster_key {",
                 '\tstyle="filled";',
                 '\tcolor="lightblue";',
                 '\tBundle [ shape="septagon" ];',
                 '\tGroup [shape="ellipse"];',
                 '\tGroup Category [shape="trapezium"];\n',
                 '\tProfile [style="bold", shape="ellipse"];',
                 '\tHblock [label="Host1|Host2|Host3",shape="record"];',
                 '\tlabel="Key";',
                 "\t}"])
        inputlist.append("}")
        idata = "\n".join(inputlist)
        try:
            result = exc.run(cmd, inputdata=idata)
        except OSError:
            # on some systems (RHEL 6), you cannot run dot with
            # shell=True.  on others (Gentoo with Python 2.7), you
            # must.  In yet others (RHEL 5), either way works.  I have
            # no idea what the difference is, but it's kind of a PITA.
            result = exc.run(cmd, shell=True, inputdata=idata)
        if not result.success:
            self.errExit("Error running %s: %s" % (cmd, result.error))
        if not setup.outfile:
            print(result.stdout)
开发者ID:feuri,项目名称:bcfg2,代码行数:43,代码来源:Admin.py

示例14: __init__

 def __init__(self, core):
     Version.__init__(self, core)
     if HAS_GITPYTHON:
         self.repo = git.Repo(Bcfg2.Options.setup.vcs_root)
         self.cmd = None
     else:
         self.logger.debug("Git: GitPython not found, using CLI interface "
                           "to Git")
         self.repo = None
         self.cmd = Executor()
     self.logger.debug("Initialized git plugin with git directory %s" %
                       self.vcs_path)
开发者ID:Ank2015,项目名称:bcfg2,代码行数:12,代码来源:Git.py

示例15: Visualize

    def Visualize(self, hosts=False, bundles=False, key=False,
                  only_client=None, output=None):
        """Build visualization of groups file."""
        if output:
            fmt = output.split('.')[-1]
        else:
            fmt = 'png'

        exc = Executor()
        cmd = ["dot", "-T", fmt]
        if output:
            cmd.extend(["-o", output])
        idata = ["digraph groups {",
                 '\trankdir="LR";',
                 self.metadata.viz(hosts, bundles,
                                   key, only_client, self.colors)]
        if key:
            idata.extend(
                ["\tsubgraph cluster_key {",
                 '\tstyle="filled";',
                 '\tcolor="lightblue";',
                 '\tBundle [ shape="septagon" ];',
                 '\tGroup [shape="ellipse"];',
                 '\tProfile [style="bold", shape="ellipse"];',
                 '\tHblock [label="Host1|Host2|Host3",shape="record"];',
                 '\tlabel="Key";',
                 "\t}"])
        idata.append("}")
        try:
            result = exc.run(cmd, inputdata=idata)
        except OSError:
            # on some systems (RHEL 6), you cannot run dot with
            # shell=True.  on others (Gentoo with Python 2.7), you
            # must.  In yet others (RHEL 5), either way works.  I have
            # no idea what the difference is, but it's kind of a PITA.
            result = exc.run(cmd, shell=True, inputdata=idata)
        if not result.success:
            print("Error running %s: %s" % (cmd, result.error))
            raise SystemExit(result.retval)
开发者ID:danfoster,项目名称:bcfg2,代码行数:39,代码来源:Viz.py


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