本文整理汇总了Python中Bcfg2.Utils.Executor.run方法的典型用法代码示例。如果您正苦于以下问题:Python Executor.run方法的具体用法?Python Executor.run怎么用?Python Executor.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类Bcfg2.Utils.Executor
的用法示例。
在下文中一共展示了Executor.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_key
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
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
示例2: Fossil
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
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)
示例3: CfgExternalCommandVerifier
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
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__
示例4: run
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
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)
示例5: Visualize
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
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)
示例6: Cvs
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class Cvs(Bcfg2.Server.Plugin.Version):
""" The Cvs plugin provides a revision interface for Bcfg2 repos
using cvs."""
__author__ = '[email protected]'
__vcs_metadata_path__ = "CVSROOT"
def __init__(self, core, datastore):
Bcfg2.Server.Plugin.Version.__init__(self, core, datastore)
self.cmd = Executor()
self.logger.debug("Initialized cvs plugin with CVS directory %s" %
self.vcs_path)
def get_revision(self):
"""Read cvs revision information for the Bcfg2 repository."""
result = self.cmd.run(["env LC_ALL=C", "cvs", "log"],
shell=True, cwd=self.vcs_root)
try:
return result.stdout.splitlines()[0].strip()
except (IndexError, AttributeError):
msg = "Failed to read revision from CVS: %s" % result.error
self.logger.error(msg)
raise Bcfg2.Server.Plugin.PluginExecutionError(msg)
示例7: Darcs
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class Darcs(Bcfg2.Server.Plugin.Version):
""" Darcs is a version plugin for dealing with Bcfg2 repos stored
in the Darcs VCS. """
__author__ = '[email protected]'
__vcs_metadata_path__ = "_darcs"
def __init__(self, core):
Bcfg2.Server.Plugin.Version.__init__(self, core)
self.cmd = Executor()
self.logger.debug("Initialized Darcs plugin with darcs directory %s" %
self.vcs_path)
def get_revision(self):
"""Read Darcs changeset information for the Bcfg2 repository."""
result = self.cmd.run(["env LC_ALL=C", "darcs", "changes"],
shell=True, cwd=Bcfg2.Options.setup.vcs_root)
if result.success:
return result.stdout.splitlines()[0].strip()
else:
msg = "Failed to read revision from darcs: %s" % result.error
self.logger.error(msg)
raise Bcfg2.Server.Plugin.PluginExecutionError(msg)
示例8: Trigger
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class Trigger(Bcfg2.Server.Plugin.Plugin,
Bcfg2.Server.Plugin.ClientRunHooks,
Bcfg2.Server.Plugin.DirectoryBacked):
"""Trigger is a plugin that calls external scripts (on the server)."""
__author__ = '[email protected]'
def __init__(self, core, datastore):
Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore)
Bcfg2.Server.Plugin.ClientRunHooks.__init__(self)
Bcfg2.Server.Plugin.DirectoryBacked.__init__(self, self.data)
self.cmd = Executor()
def async_run(self, args):
""" Run the trigger script asynchronously in a forked process
"""
pid = os.fork()
if pid:
os.waitpid(pid, 0)
else:
dpid = os.fork()
if not dpid:
self.debug_log("Running %s" % " ".join(pipes.quote(a)
for a in args))
result = self.cmd.run(args)
if not result.success:
self.logger.error("Trigger: Error running %s: %s" %
(args[0], result.error))
elif result.stderr:
self.debug_log("Trigger: Error: %s" % result.stderr)
os._exit(0) # pylint: disable=W0212
def end_client_run(self, metadata):
args = [metadata.hostname, '-p', metadata.profile, '-g',
':'.join([g for g in metadata.groups])]
for notifier in self.entries.keys():
npath = os.path.join(self.data, notifier)
self.async_run([npath] + args)
示例9: YumCollection
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class YumCollection(Collection):
""" Handle collections of Yum sources. If we're using the yum
Python libraries, then this becomes a very full-featured
:class:`Bcfg2.Server.Plugins.Packages.Collection.Collection`
object; if not, then it defers to the :class:`YumSource`
object.
.. private-include: _add_gpg_instances, _get_pulp_consumer
"""
#: Options that are included in the [packages:yum] section of the
#: config but that should not be included in the temporary
#: yum.conf we write out
option_blacklist = ["use_yum_libraries", "helper"]
#: :class:`PulpCertificateSet` object used to handle Pulp certs
pulp_cert_set = None
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)
@property
def __package_groups__(self):
return True
@property
def helper(self):
""" The full path to :file:`bcfg2-yum-helper`. First, we
check in the config file to see if it has been explicitly
specified; next we see if it's in $PATH (which we do by making
a call to it; I wish there was a way to do this without
forking, but apparently not); finally we check in /usr/sbin,
the default location. """
if not self._helper:
try:
self._helper = self.setup.cfp.get("packages:yum", "helper")
except (ConfigParser.NoOptionError, ConfigParser.NoSectionError):
# first see if bcfg2-yum-helper is in PATH
try:
self.debug_log("Checking for bcfg2-yum-helper in $PATH")
self.cmd.run(["bcfg2-yum-helper"])
self._helper = "bcfg2-yum-helper"
except OSError:
self._helper = "/usr/sbin/bcfg2-yum-helper"
return self._helper
@property
def use_yum(self):
""" True if we should use the yum Python libraries, False
otherwise """
return HAS_YUM and self.setup.cfp.getboolean("packages:yum", "use_yum_libraries", default=False)
@property
def has_pulp_sources(self):
""" True if there are any Pulp sources to handle, False
otherwise """
return any(s.pulp_id for s in self)
@property
def cachefiles(self):
""" A list of the full path to all cachefiles used by this
collection."""
cachefiles = set(Collection.cachefiles.fget(self))
if self.cachefile:
cachefiles.add(self.cachefile)
return list(cachefiles)
@track_statistics()
#.........这里部分代码省略.........
示例10: Svn
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
#.........这里部分代码省略.........
# pylint: enable=W0613
def ssl_server_trust_prompt(self, trust_dict):
""" PySvn callback to always trust SSL certificates from SVN server """
self.logger.debug("Svn: Trusting SSL certificate from %s, "
"issued by %s for realm %s" %
(trust_dict['hostname'],
trust_dict['issuer_dname'],
trust_dict['realm']))
return True, trust_dict['failures'], False
def get_conflict_resolver(self, choice):
""" Get a PySvn conflict resolution callback """
def callback(conflict_description):
""" PySvn callback function to resolve conflicts """
self.logger.info("Svn: Resolving conflict for %s with %s" %
(conflict_description['path'], choice))
return choice, None, False
return callback
def get_revision(self):
"""Read svn revision information for the Bcfg2 repository."""
msg = None
if HAS_SVN:
try:
info = self.client.info(self.vcs_root)
self.revision = info.revision
self.svn_root = info.url
return str(self.revision.number)
except pysvn.ClientError: # pylint: disable=E1101
msg = "Svn: Failed to get revision: %s" % sys.exc_info()[1]
else:
result = self.cmd.run(["env LC_ALL=C", "svn", "info",
self.vcs_root],
shell=True)
if result.success:
self.revision = [line.split(': ')[1]
for line in result.stdout.splitlines()
if line.startswith('Revision:')][-1]
return self.revision
else:
msg = "Failed to read svn info: %s" % result.error
self.revision = None
raise Bcfg2.Server.Plugin.PluginExecutionError(msg)
def Update(self):
'''Svn.Update() => True|False\nUpdate svn working copy\n'''
try:
old_revision = self.revision.number
self.revision = self.client.update(self.vcs_root, recurse=True)[0]
except pysvn.ClientError: # pylint: disable=E1101
err = sys.exc_info()[1]
# try to be smart about the error we got back
details = None
if "callback_ssl_server_trust_prompt" in str(err):
details = "SVN server certificate is not trusted"
elif "callback_get_login" in str(err):
details = "SVN credentials not cached"
if details is None:
self.logger.error("Svn: Failed to update server repository",
exc_info=1)
else:
self.logger.error("Svn: Failed to update server repository: "
"%s" % details)
示例11: Git
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class Git(Version):
""" The Git plugin provides a revision interface for Bcfg2 repos
using git. """
__author__ = '[email protected]'
__vcs_metadata_path__ = ".git"
if HAS_GITPYTHON:
__rmi__ = Version.__rmi__ + ['Update']
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)
def _log_git_cmd(self, output):
""" Send output from a GitPython command to the debug log """
for line in output.strip().splitlines():
self.debug_log("Git: %s" % line)
def get_revision(self):
"""Read git revision information for the Bcfg2 repository."""
if HAS_GITPYTHON:
return self.repo.head.commit.hexsha
else:
cmd = ["git", "--git-dir", self.vcs_path,
"--work-tree", Bcfg2.Options.setup.vcs_root,
"rev-parse", "HEAD"]
self.debug_log("Git: Running %s" % cmd)
result = self.cmd.run(cmd)
if not result.success:
raise PluginExecutionError(result.stderr)
return result.stdout
def Update(self, ref=None):
""" Git.Update() => True|False
Update the working copy against the upstream repository
"""
self.logger.info("Git: Git.Update(ref='%s')" % ref)
self.debug_log("Git: Performing garbage collection on repo at %s" %
Bcfg2.Options.setup.vcs_root)
try:
self._log_git_cmd(self.repo.git.gc('--auto'))
except git.GitCommandError:
self.logger.warning("Git: Failed to perform garbage collection: %s"
% sys.exc_info()[1])
self.debug_log("Git: Fetching all refs for repo at %s" %
Bcfg2.Options.setup.vcs_root)
try:
self._log_git_cmd(self.repo.git.fetch('--all'))
except git.GitCommandError:
self.logger.warning("Git: Failed to fetch refs: %s" %
sys.exc_info()[1])
if ref:
self.debug_log("Git: Checking out %s" % ref)
try:
self._log_git_cmd(self.repo.git.checkout('-f', ref))
except git.GitCommandError:
raise PluginExecutionError("Git: Failed to checkout %s: %s" %
(ref, sys.exc_info()[1]))
# determine if we should try to pull to get the latest commit
# on this head
tracking = None
if not self.repo.head.is_detached:
self.debug_log("Git: Determining if %s is a tracking branch" %
self.repo.head.ref.name)
tracking = self.repo.head.ref.tracking_branch()
if tracking is not None:
self.debug_log("Git: %s is a tracking branch, pulling from %s" %
(self.repo.head.ref.name, tracking))
try:
self._log_git_cmd(self.repo.git.pull("--rebase"))
except git.GitCommandError:
raise PluginExecutionError("Git: Failed to pull from "
"upstream: %s" % sys.exc_info()[1])
self.logger.info("Git: Repo at %s updated to %s" %
(Bcfg2.Options.setup.vcs_root, self.get_revision()))
return True
示例12: Client
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class Client(object):
""" The main Bcfg2 client class """
options = Proxy.ComponentProxy.options + [
Bcfg2.Options.Common.syslog,
Bcfg2.Options.Common.interactive,
Bcfg2.Options.BooleanOption(
"-q", "--quick", help="Disable some checksum verification"),
Bcfg2.Options.Option(
cf=('client', 'probe_timeout'),
type=Bcfg2.Options.Types.timeout,
help="Timeout when running client probes"),
Bcfg2.Options.Option(
"-b", "--only-bundles", default=[],
type=Bcfg2.Options.Types.colon_list,
help='Only configure the given bundle(s)'),
Bcfg2.Options.Option(
"-B", "--except-bundles", default=[],
type=Bcfg2.Options.Types.colon_list,
help='Configure everything except the given bundle(s)'),
Bcfg2.Options.ExclusiveOptionGroup(
Bcfg2.Options.BooleanOption(
"-Q", "--bundle-quick",
help='Only verify the given bundle(s)'),
Bcfg2.Options.Option(
'-r', '--remove',
choices=['all', 'services', 'packages', 'users'],
help='Force removal of additional configuration items')),
Bcfg2.Options.ExclusiveOptionGroup(
Bcfg2.Options.PathOption(
'-f', '--file', type=argparse.FileType('rb'),
help='Configure from a file rather than querying the server'),
Bcfg2.Options.PathOption(
'-c', '--cache', type=argparse.FileType('wb'),
help='Store the configuration in a file')),
Bcfg2.Options.BooleanOption(
'--exit-on-probe-failure', default=True,
cf=('client', 'exit_on_probe_failure'),
help="The client should exit if a probe fails"),
Bcfg2.Options.Option(
'-p', '--profile', cf=('client', 'profile'),
help='Assert the given profile for the host'),
Bcfg2.Options.Option(
'-l', '--decision', cf=('client', 'decision'),
choices=['whitelist', 'blacklist', 'none'],
help='Run client in server decision list mode'),
Bcfg2.Options.BooleanOption(
"-O", "--no-lock", help='Omit lock check'),
Bcfg2.Options.PathOption(
cf=('components', 'lockfile'), default='/var/lock/bcfg2.run',
help='Client lock file'),
Bcfg2.Options.BooleanOption(
"-n", "--dry-run", help='Do not actually change the system'),
Bcfg2.Options.Option(
"-D", "--drivers", cf=('client', 'drivers'),
type=Bcfg2.Options.Types.comma_list,
default=[m[1] for m in walk_packages(path=Tools.__path__)],
action=ClientDriverAction, help='Client drivers'),
Bcfg2.Options.BooleanOption(
"-e", "--show-extra", help='Enable extra entry output'),
Bcfg2.Options.BooleanOption(
"-k", "--kevlar", help='Run in bulletproof mode'),
Bcfg2.Options.BooleanOption(
"-i", "--only-important",
help='Only configure the important entries')]
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__)
def _probe_failure(self, probename, msg):
""" handle failure of a probe in the way the user wants us to
(exit or continue) """
#.........这里部分代码省略.........
示例13: SSHbase
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
#.........这里部分代码省略.........
if event.filename == "info.xml":
for entry in list(self.entries.values()):
entry.handle_event(event)
return
if event.filename.endswith(".static"):
self.logger.info("Static key %s %s; invalidating ssh_known_hosts " "cache" % (event.filename, action))
if action == "deleted" and event.filename in self.static:
del self.static[event.filename]
self.skn = False
else:
self.static[event.filename] = Bcfg2.Server.Plugin.FileBacked(os.path.join(self.data, event.filename))
self.static[event.filename].HandleEvent(event)
self.skn = False
return
self.logger.warn("SSHbase: Got unknown event %s %s" % (event.filename, action))
def get_ipcache_entry(self, client):
""" Build a cache of dns results. """
if client in self.ipcache:
if self.ipcache[client]:
return self.ipcache[client]
else:
raise PluginExecutionError("No cached IP address for %s" % client)
else:
# need to add entry
try:
ipaddr = socket.gethostbyname(client)
self.ipcache[client] = (ipaddr, client)
return (ipaddr, client)
except socket.gaierror:
result = self.cmd.run(["getent", "hosts", client])
if result.success:
ipaddr = result.stdout.strip().split()
if ipaddr:
self.ipcache[client] = (ipaddr, client)
return (ipaddr, client)
self.ipcache[client] = False
msg = "Failed to find IP address for %s: %s" % (client, result.error)
self.logger(msg)
raise PluginExecutionError(msg)
def get_namecache_entry(self, cip):
"""Build a cache of name lookups from client IP addresses."""
if cip in self.namecache:
# lookup cached name from IP
if self.namecache[cip]:
return self.namecache[cip]
else:
raise socket.gaierror
else:
# add an entry that has not been cached
try:
rvlookup = socket.gethostbyaddr(cip)
if rvlookup[0]:
self.namecache[cip] = [rvlookup[0]]
else:
self.namecache[cip] = []
self.namecache[cip].extend(rvlookup[1])
return self.namecache[cip]
except socket.gaierror:
self.namecache[cip] = False
self.logger.error("Failed to find any names associated with " "IP address %s" % cip)
raise
示例14: SSLCAEntrySet
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class SSLCAEntrySet(Bcfg2.Server.Plugin.EntrySet):
""" Entry set to handle SSLCA entries and XML files """
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)
def handle_event(self, event):
action = event.code2str()
fpath = os.path.join(self.path, event.filename)
if event.filename == 'key.xml':
if action in ['exists', 'created', 'changed']:
self.key = SSLCAKeySpec(fpath)
self.key.HandleEvent(event)
elif event.filename == 'cert.xml':
if action in ['exists', 'created', 'changed']:
self.cert = SSLCACertSpec(fpath)
self.cert.HandleEvent(event)
else:
Bcfg2.Server.Plugin.EntrySet.handle_event(self, event)
def build_key(self, entry, metadata):
"""
either grabs a prexisting key hostfile, or triggers the generation
of a new key if one doesn't exist.
"""
# TODO: verify key fits the specs
filename = "%s.H_%s" % (os.path.basename(entry.get('name')),
metadata.hostname)
self.logger.info("SSLCA: Generating new key %s" % filename)
key_spec = self.key.get_spec(metadata)
ktype = key_spec['type']
bits = key_spec['bits']
if ktype == 'rsa':
cmd = ["openssl", "genrsa", bits]
elif ktype == 'dsa':
cmd = ["openssl", "dsaparam", "-noout", "-genkey", bits]
self.debug_log("SSLCA: Generating new key: %s" % " ".join(cmd))
result = self.cmd.run(cmd)
if not result.success:
raise PluginExecutionError("SSLCA: Failed to generate key %s for "
"%s: %s" % (entry.get("name"),
metadata.hostname,
result.error))
open(os.path.join(self.path, filename), 'w').write(result.stdout)
return result.stdout
def build_cert(self, entry, metadata, keyfile):
""" generate a new cert """
filename = "%s.H_%s" % (os.path.basename(entry.get('name')),
metadata.hostname)
self.logger.info("SSLCA: Generating new cert %s" % filename)
cert_spec = self.cert.get_spec(metadata)
ca = self.parent.get_ca(cert_spec['ca'])
req_config = None
req = None
try:
req_config = self.build_req_config(metadata)
req = self.build_request(keyfile, req_config, metadata)
days = cert_spec['days']
cmd = ["openssl", "ca", "-config", ca['config'], "-in", req,
"-days", days, "-batch"]
passphrase = ca.get('passphrase')
if passphrase:
cmd.extend(["-passin", "pass:%s" % passphrase])
def _scrub_pass(arg):
""" helper to scrub the passphrase from the
argument list """
if arg.startswith("pass:"):
return "pass:******"
else:
return arg
else:
_scrub_pass = lambda a: a
self.debug_log("SSLCA: Generating new certificate: %s" %
" ".join(_scrub_pass(a) for a in cmd))
result = self.cmd.run(cmd)
if not result.success:
raise PluginExecutionError("SSLCA: Failed to generate cert: %s"
% result.error)
finally:
try:
if req_config and os.path.exists(req_config):
os.unlink(req_config)
if req and os.path.exists(req):
os.unlink(req)
except OSError:
self.logger.error("SSLCA: Failed to unlink temporary files: %s"
% sys.exc_info()[1])
cert = result.stdout
if cert_spec['append_chain'] and 'chaincert' in ca:
cert += open(ca['chaincert']).read()
open(os.path.join(self.path, filename), 'w').write(cert)
#.........这里部分代码省略.........
示例15: Svn
# 需要导入模块: from Bcfg2.Utils import Executor [as 别名]
# 或者: from Bcfg2.Utils.Executor import run [as 别名]
class Svn(Bcfg2.Server.Plugin.Version):
"""Svn is a version plugin for dealing with Bcfg2 repos."""
options = Bcfg2.Server.Plugin.Version.options + [
Bcfg2.Options.Option(
cf=("svn", "conflict_resolution"), dest="svn_conflict_resolution",
type=lambda v: v.replace("-", "_"),
choices=dir(pysvn.wc_conflict_choice),
default=pysvn.wc_conflict_choice.postpone,
help="SVN conflict resolution method"),
Bcfg2.Options.Option(
cf=("svn", "user"), dest="svn_user", help="SVN username"),
Bcfg2.Options.Option(
cf=("svn", "password"), dest="svn_password", help="SVN password"),
Bcfg2.Options.BooleanOption(
cf=("svn", "always_trust"), dest="svn_trust_ssl",
help="Always trust SSL certs from SVN server")]
__author__ = '[email protected]'
__vcs_metadata_path__ = ".svn"
if HAS_SVN:
__rmi__ = Bcfg2.Server.Plugin.Version.__rmi__ + ['Update', 'Commit']
else:
__vcs_metadata_path__ = ".svn"
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)
def get_login(self, realm, username, may_save): # pylint: disable=W0613
""" PySvn callback to get credentials for HTTP basic authentication """
self.logger.debug("Svn: Logging in with username: %s" %
Bcfg2.Options.setup.svn_user)
return (True,
Bcfg2.Options.setup.svn_user,
Bcfg2.Options.setup.svn_password,
False)
def ssl_server_trust_prompt(self, trust_dict):
""" PySvn callback to always trust SSL certificates from SVN server """
self.logger.debug("Svn: Trusting SSL certificate from %s, "
"issued by %s for realm %s" %
(trust_dict['hostname'],
trust_dict['issuer_dname'],
trust_dict['realm']))
return True, trust_dict['failures'], False
def conflict_resolver(self, conflict_description):
""" PySvn callback function to resolve conflicts """
self.logger.info("Svn: Resolving conflict for %s with %s" %
(conflict_description['path'],
Bcfg2.Options.setup.svn_conflict_resolution))
return Bcfg2.Options.setup.svn_conflict_resolution, None, False
def get_revision(self):
"""Read svn revision information for the Bcfg2 repository."""
msg = None
if HAS_SVN:
try:
info = self.client.info(Bcfg2.Options.setup.vcs_root)
self.revision = info.revision
self.svn_root = info.url
return str(self.revision.number)
except pysvn.ClientError: # pylint: disable=E1101
msg = "Svn: Failed to get revision: %s" % sys.exc_info()[1]
else:
result = self.cmd.run(["env LC_ALL=C", "svn", "info",
Bcfg2.Options.setup.vcs_root],
shell=True)
if result.success:
self.revision = [line.split(': ')[1]
for line in result.stdout.splitlines()
if line.startswith('Revision:')][-1]
return self.revision
else:
msg = "Failed to read svn info: %s" % result.error
self.revision = None
#.........这里部分代码省略.........