本文整理汇总了Python中salt.client.cmd函数的典型用法代码示例。如果您正苦于以下问题:Python cmd函数的具体用法?Python cmd怎么用?Python cmd使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了cmd函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: migrate
def migrate(name, target=''):
'''
Migrate a vm from one hypervisor to another. This routine will just start
the migration and display information on how to look up the progress.
'''
client = salt.client.get_local_client(__opts__['conf_file'])
data = query(quiet=True)
origin_data = _find_vm(name, data, quiet=True)
try:
origin_hyper = list(origin_data.keys())[0]
except IndexError:
__jid_event__.fire_event({'error': 'Named vm {0} was not found to migrate'.format(name)}, 'progress')
return ''
disks = origin_data[origin_hyper][name]['disks']
if not origin_data:
__jid_event__.fire_event({'error': 'Named vm {0} was not found to migrate'.format(name)}, 'progress')
return ''
if not target:
target = _determine_hyper(data, origin_hyper)
if target not in data:
__jid_event__.fire_event({'error': 'Target hypervisor {0} not found'.format(origin_data)}, 'progress')
return ''
try:
client.cmd(target, 'virt.seed_non_shared_migrate', [disks, True])
jid = client.cmd_async(origin_hyper,
'virt.migrate_non_shared',
[name, target])
except SaltClientError as client_error:
return 'Virtual machine {0} could not be migrated: {1}'.format(name, client_error)
msg = ('The migration of virtual machine {0} to hypervisor {1} has begun, '
'and can be tracked via jid {2}. The ``salt-run virt.query`` '
'runner can also be used, the target vm will be shown as paused '
'until the migration is complete.').format(name, target, jid)
__jid_event__.fire_event({'message': msg}, 'progress')
示例2: migrate
def migrate(name, target=""):
"""
Migrate a vm from one hypervisor to another. This routine will just start
the migration and display information on how to look up the progress.
"""
client = salt.client.get_local_client(__opts__["conf_file"])
data = query(quiet=True)
origin_data = _find_vm(name, data, quiet=True)
try:
origin_hyper = origin_data.iterkeys().next()
except StopIteration:
print("Named vm {0} was not found to migrate".format(name))
return ""
disks = origin_data[origin_hyper][name]["disks"]
if not origin_data:
print("Named vm {0} was not found to migrate".format(name))
return ""
if not target:
target = _determine_hyper(data, origin_hyper)
if target not in data:
print("Target hypervisor {0} not found".format(origin_data))
return ""
client.cmd(target, "virt.seed_non_shared_migrate", [disks, True])
jid = client.cmd_async(origin_hyper, "virt.migrate_non_shared", [name, target])
msg = (
"The migration of virtual machine {0} to hypervisor {1} has begun, "
"and can be tracked via jid {2}. The ``salt-run virt.query`` "
"runner can also be used, the target vm will be shown as paused "
"until the migration is complete."
).format(name, target, jid)
print(msg)
示例3: main
def main():
cmd = 'cd /var/www; php /var/www/multiprocess.php '
for i in range(0, 10):
for j in range(0, 5):
result = client.cmd('web-mongo*.hsng.org',
'cmd.run',
[cmd + str(i + 1)],
20 * (i + 1))
if j != 0:
sys.stdout.write(',')
sys.stdout.write(str(_max(result)))
# print(result)
sleep(5)
print('')
print('')
for i in range(0, 10):
for j in range(0, 5):
result = client.cmd('web-mysql*.hsng.org',
'cmd.run',
[cmd + str(i + 1)],
40 * (i + 1))
if j != 0:
sys.stdout.write(',')
sys.stdout.write(str(_max(result)))
# print(result)
sleep(5)
print('')
示例4: migrate
def migrate(name, target=''):
'''
Migrate a vm from one hypervisor to another. This routine will just start
the migration and display information on how to look up the progress
'''
client = salt.client.LocalClient(__opts__['conf_file'])
data = query(quiet=True)
origin_data = _find_vm(name, data, quiet=True)
try:
origin_hyper = origin_data.keys()[0]
except IndexError:
print('Named vm {0} was not found to migrate'.format(name))
return ''
disks = origin_data[origin_hyper][name]['disks']
if not origin_data:
print('Named vm {0} was not found to migrate'.format(name))
return ''
if not target:
target = _determine_hyper(data, origin_hyper)
if target not in data:
print('Target hypervisor {0} not found'.format(origin_data))
return ''
client.cmd(target, 'virt.seed_non_shared_migrate', [disks, True])
print(client.cmd_async(origin_hyper,
'virt.migrate_non_shared',
[name, target]))
示例5: info
def info(client, instance):
"""
Shows whether an instance of LAVA is running or not on its configured hosts.
"""
cmd = 'status lava-instance LAVA_INSTANCE={0}'.format(instance)
inst_path = '/srv/lava/instances/{0}'.format(instance)
worker_file = '{0}/sbin/mount-masterfs'.format(inst_path)
inf = {}
ret = client.cmd('*', 'lava.list_instances', [])
for k, v in ret.iteritems():
if inst_path in v:
ret = client.cmd(k, 'cmd.run', [cmd])
running = UNKNOWN
if ret[k] == 'status: Unknown instance: %s' % instance:
running = STOPPED
elif ret[k] == 'lava-instance (%s) start/running' % instance:
running = RUNNING
ret = client.cmd(k, 'file.file_exists', [worker_file])
master = not ret[k]
inf[k] = {'running': running, 'master': master}
return inf
示例6: post
def post(self):
slave_1 =self.get_argument("slave_1")
config_name_1 =self.get_argument("config_name_1")
config_conteny_1 =self.get_argument("config_conteny_1")
slave_2 =self.get_argument("slave_2")
config_name_2 =self.get_argument("config_name_2")
config_conteny_2 =self.get_argument("config_conteny_2")
client = salt.client.LocalClient()
f_1=open(config_name_1,'a')
f_1.write(config_conteny_1)
f_1.close()
shell_commond_1='/usr/bin/salt-cp -L \'%s\' %s /data/server/redis/etc/ ' %(slave_1,config_name_1)
shell_commond_2='/usr/bin/salt-cp -L \'%s\' %s /data/server/redis/etc/ ' %(slave_2,config_name_1)
a_1,b_1 = commands.getstatusoutput(shell_commond_1)
a_2,b_2 = commands.getstatusoutput(shell_commond_2)
os.remove(config_name_1)
if a_1 != 0:
self.write(str("%上传失败"%slave_1))
if a_2 != 0:
self.write(str("%上传失败"%slave_2))
#启动redis服务
start_server="/data/server/redis/bin/redis-server /data/server/redis/etc/%s "%config_name_1
ret_1 = client.cmd(slave_1.encode('utf-8'), 'cmd.run', [start_server])
ret_2 = client.cmd(slave_2.encode('utf-8'), 'cmd.run', [start_server])
print ret_1,ret_2
self.write(str("%s上新的redis实例启动成功\n%s上新的redis实例启动成功"%(ret_1,ret_2)))
示例7: os_info
def os_info():
ret = client.cmd('*', 'grains.items')
for k, v in ret.iteritems():
labconfig[k]['grains'] = v
ret = client.cmd('*', 'disk.usage')
for k, v in ret.iteritems():
labconfig[k]['disk'] = v
示例8: git_pull
def git_pull(target, path, rev):
import salt.client
client = salt.client.LocalClient()
# Fetch first
client.cmd(target, 'git.pull', [path, '--all'])
# Then checkout
client.cmd(target, 'git.checkout', [path, rev])
示例9: ready
def ready(**kwargs):
"""
Wait for minions to respond. Compare test.ping results to either
the list of all accepted keys or search criteria of cached pillar
data.
"""
settings = {
'timeout': None,
'search': None,
'sleep': 6
}
settings.update(kwargs)
ret = {}
#client = salt.client.get_local_client(__opts__['conf_file'])
end_time = None
if settings['timeout']:
end_time = time.time() + settings['timeout']
log.debug("end time: {}".format(end_time))
client = salt.client.LocalClient()
while True:
try:
if settings['search']:
results = client.cmd(settings['search'], 'test.ping', timeout=__opts__['timeout'], expr_form="compound")
else:
results = client.cmd('*', 'test.ping', timeout=__opts__['timeout'])
except SaltClientError as client_error:
print(client_error)
return ret
actual = set(results.keys())
if settings['search']:
pillar_util = salt.utils.master.MasterPillarUtil(settings['search'], "compound",
use_cached_grains=True,
grains_fallback=False,
opts=__opts__)
cached = pillar_util.get_minion_pillar()
expected = set(cached.keys())
else:
key = salt.key.Key(__opts__)
expected = set(key.list_keys()['minions'])
if actual == expected:
log.warn("All minions are ready")
break
log.warn("Waiting on {}".format(",".join(list(expected - actual))))
if end_time:
if end_time < time.time():
log.warn("Timeout reached")
return False
time.sleep(settings['sleep'])
return True
示例10: restart_samba_services
def restart_samba_services():
client = salt.client.LocalClient()
rc = client.cmd('*', 'service.reload', ['smbd'] )
print rc
rc = client.cmd('*', 'service.restart', ['winbind'] )
print rc
#rc = client.cmd('*', 'service.restart', ['nmbd'] )
#print rc
return
示例11: upgrade
def upgrade(client, instance, dry_run=True):
"""
Runs lava-deployment-tool upgrade for a LAVA setup. It first shuts down
each worker node instance. Then it runs lava-deployment-tool upgrade on
the master. Lastly, it runs lava-deployment-tool upgradeworker on the
worker nodes.
"""
timeout = 300 # 5 minutes
workers = []
master = None
for host, props in info(client, instance).iteritems():
if props['master']:
assert not master, 'Detected multiple master instances in LAVA deployment'
master = host
else:
workers.append(host)
assert master, 'No master instance found in LAVA deployment'
w_ret = {}
for h in workers:
w_ret[h] = {'stop': 'dry-run', 'upgrade': 'dry-run', 'start': 'dry-run'}
if dry_run:
m_ret = {master: 'dry-run: upgrade master'}
return m_ret, w_ret
# first stop workers. This prevents a DB error if the upgrade changes
# the schema.
ret = stop(client, instance, True)
if ret:
for host, msg in ret.iteritems():
w_ret[host]['stop'] = msg
# now upgrade the master node
cmd = 'SKIP_ROOT_CHECK=yes {0} upgrade {1}'.format(LDT, instance)
m_ret = client.cmd(master, 'cmd.run', [cmd], timeout=timeout)
# now upgrade the workers
cmd = 'SKIP_ROOT_CHECK=yes {0} upgradeworker {1}'.format(LDT, instance)
if len(workers):
ret = client.cmd(workers, 'cmd.run', [cmd], timeout=timeout, expr_form='list')
for host, msg in ret.iteritems():
w_ret[host]['upgrade'] = msg
ret = start(client, instance)
if ret:
for host, msg in ret.iteritems():
if host in w_ret:
w_ret[host]['start'] = msg
# last thing: l-d-t ran as root, lets chmod things
cmd = 'chown -R instance-manager:instance-manager /srv/lava/instances/{0}/code/*'.format(instance)
client.cmd(workers + [master], 'cmd.run', [cmd], expr_form='list')
return m_ret, w_ret
示例12: get_file
def get_file(self,hn, fname):
f = client.cmd(hn, 'file.file_exists',[fname])
t = (f[hn])
if t is True:
k = fname.split('/')
fi = k[-1]
client.cmd(hn,'file.rename',[fname,'/data/deploy/%s/%s' % (date,fi+'-'+time)])
c = client.cmd(hn, 'cp.get_file', ['salt:/%s' % fname, fname])
print c
示例13: ping_all_connected_minions
def ping_all_connected_minions(opts):
client = salt.client.LocalClient()
if opts['minion_data_cache']:
tgt = list(salt.utils.minions.CkMinions(opts).connected_ids())
form = 'list'
else:
tgt = '*'
form = 'glob'
client.cmd(tgt, 'test.ping', tgt_type=form)
示例14: write_highstate_runner_claim
def write_highstate_runner_claim(minion_id):
'''Write our saltmaster's id into a file on the minion, designating which saltmaster gets to run the
highstate on it. First in wins.
/tmp/highstate_runner'''
client = salt.client.LocalClient()
path = "/tmp/highstate_runner"
hostname = socket.gethostname()
results = client.cmd(tgt=minion_id, fun='file.touch', arg=[path]) # sync call
results_by_minion = client.cmd(tgt=minion_id, fun='file.append', arg=[path, hostname]) # sync call
return
示例15: write_highstate_ran
def write_highstate_ran(minion_id):
'''Write our saltmaster's id into a file on the minion, designating which saltmaster gets to run the
highstate on it. First in wins.
/tmp/highstate_runner'''
client = salt.client.LocalClient()
path = "/etc/salt/highstate_ran_once"
seconds = time.time()
results = client.cmd(tgt=minion_id, fun='file.touch', arg=[path]) # sync call
results_by_minion = client.cmd(tgt=minion_id, fun='file.append', arg=[path, seconds]) # sync call
return