本文整理汇总了Python中wok.utils.run_command函数的典型用法代码示例。如果您正苦于以下问题:Python run_command函数的具体用法?Python run_command怎么用?Python run_command使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了run_command函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: activate
def activate(self, ifacename):
wok_log.info('Bring up an interface ' + ifacename)
iface_type = netinfo.get_interface_type(ifacename)
if iface_type == "Ethernet":
cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
out, error, returncode = run_command(cmd_ipup)
if returncode != 0:
wok_log.error(
'Unable to bring up the interface on ' + ifacename +
', ' + error)
raise OperationFailed('GINNET0059E', {'name': ifacename,
'error': error})
# Some times based on system load, it takes few seconds to
# reflect the /sys/class/net files upon execution of 'ip link
# set' command. Following snippet is to wait util files get
# reflect.
timeout = self.wait_time(ifacename)
if timeout == 5:
wok_log.warn("Time-out has happened upon execution of 'ip "
"link set <interface> up', hence behavior of "
"activating an interface may not as expected.")
else:
wok_log.info(
'Successfully brought up the interface ' + ifacename)
wok_log.info('Activating an interface ' + ifacename)
cmd_ifup = ['ifup', '%s' % ifacename]
out, error, returncode = run_command(cmd_ifup)
if returncode != 0:
wok_log.error(
'Unable to activate the interface on ' + ifacename +
', ' + error)
raise OperationFailed('GINNET0016E',
{'name': ifacename, 'error': error})
wok_log.info(
'Connection successfully activated for the interface ' + ifacename)
示例2: get_sels
def get_sels(server):
sels = []
serverData = get_config(server)
if serverData:
password = serverData['password']
ipaddr = serverData['ipaddr']
salt = serverData['salt']
if serverData.get('username'):
out, err, rc = run_command(
['ipmitool', '-H', ipaddr, '-I', 'lanplus', '-U',
serverData['username'], '-P', decrypt(password, salt),
'sel', 'list'])
else:
out, err, rc = run_command(
['ipmitool', '-H', ipaddr, '-I', 'lanplus', '-P',
decrypt(password, salt), 'sel', 'list'])
if rc == 0:
output = out.rstrip().split('\n')
for each in output:
sels.append(get_each_sel(each))
else:
raise OperationFailed(
'GINSEL00001E',
{'name': server,
'err': err,
'rc': rc})
else:
raise OperationFailed('GINSEL00002E', {'name': server})
return sels
示例3: _update_lvm_disks
def _update_lvm_disks(self, pool_name, disks):
# check if all the disks/partitions exists in the host
for disk in disks:
lsblk_cmd = ['lsblk', disk]
output, error, returncode = run_command(lsblk_cmd)
if returncode != 0:
wok_log.error(
'%s is not a valid disk/partition. Could not '
'add it to the pool %s.',
disk,
pool_name,
)
raise OperationFailed(
'KCHPOOL0027E', {'disk': disk, 'pool': pool_name})
# add disks to the lvm pool using vgextend + virsh refresh
vgextend_cmd = ['vgextend', pool_name]
vgextend_cmd += disks
output, error, returncode = run_command(vgextend_cmd)
if returncode != 0:
msg = 'Could not add disks to pool %s, error: %s'
wok_log.error(msg, pool_name, error)
raise OperationFailed(
'KCHPOOL0028E', {'pool': pool_name, 'err': error})
# refreshing pool state
pool = self.get_storagepool(pool_name, self.conn)
if pool.isActive():
pool.refresh(0)
示例4: prepare
def prepare(self, conn):
mnt_point = tempfile.mkdtemp(dir='/tmp')
export_path = "%s:%s" % (
self.poolArgs['source']['host'], self.poolArgs['source']['path'])
mount_cmd = ["mount", "-o", 'soft,timeo=100,retrans=3,retry=0',
export_path, mnt_point]
umount_cmd = ["umount", "-f", export_path]
mounted = False
# Due to an NFS bug (See Red Hat BZ 1023059), NFSv4 exports may take
# 10-15 seconds to mount the first time.
cmd_timeout = 15
with RollbackContext() as rollback:
rollback.prependDefer(os.rmdir, mnt_point)
try:
run_command(mount_cmd, cmd_timeout)
rollback.prependDefer(run_command, umount_cmd, cmd_timeout)
except TimeoutExpired:
raise InvalidParameter("KCHPOOL0012E", {'path': export_path})
with open("/proc/mounts", "rb") as f:
rawMounts = f.read()
output_items = ['dev_path', 'mnt_point', 'type']
mounts = parse_cmd_output(rawMounts, output_items)
for item in mounts:
if 'dev_path' in item and item['dev_path'] == export_path:
mounted = True
if not mounted:
raise InvalidParameter("KCHPOOL0013E", {'path': export_path})
示例5: change_dasdpart_type
def change_dasdpart_type(part, type):
"""
Change the type of the dasd partition
:param part: name of the dasd partition e.g. dasd1
:param type: partition type to be changed to e.g 4 (Linux LVM type)
:return:
"""
part_details = re.search(r'(dasd[a-zA-Z]+)(\d+)', part)
if not part_details:
raise OperationFailed('GINDASDPAR0011E', {'name': part})
devname, partnum = part_details.groups()
devname = '/dev/' + devname
typ_str = '\nt\n' + partnum + '\n' + type + '\n' + 'w\n'
p1_out = subprocess.Popen(["echo", "-e", "\'", typ_str, "\'"],
stdout=subprocess.PIPE)
p2_out = subprocess.Popen(["fdasd", devname], stdin=p1_out.stdout,
stderr=subprocess.PIPE, stdout=subprocess.PIPE)
p1_out.stdout.close()
out, err = p2_out.communicate()
if p2_out.returncode != 0:
if 'error while rereading partition table' in err.lower():
run_command(["partprobe", devname, "-s"])
else:
raise OperationFailed("GINDASDPAR0014E", {'err': err})
return
示例6: delete_sel
def delete_sel(server, sel_id):
serverData = get_config(server)
sel_id_int = int(sel_id, 16)
if serverData:
password = serverData['password']
ipaddr = serverData['ipaddr']
salt = serverData['salt']
if serverData.get('username'):
out, err, rc = run_command(
['ipmitool', '-H', ipaddr, '-I', 'lanplus', '-U',
serverData['username'], '-P', decrypt(password, salt),
'sel', 'delete', str(sel_id_int)])
else:
out, err, rc = run_command(
['ipmitool', '-H', ipaddr, '-I', 'lanplus', '-P',
decrypt(password, salt), 'sel', 'delete', str(sel_id_int)])
if rc != 0:
raise OperationFailed(
'GINSEL00004E',
{'name': server,
'sel_id': sel_id,
'err': err,
'rc': rc})
else:
raise OperationFailed('GINSEL00002E', {'name': server})
示例7: server_power_cycle
def server_power_cycle(serverData, cmd):
count = 0
if 'username' in serverData.keys() and serverData['username']:
out, err, rc = run_command(
['ipmitool', '-H', serverData['ipaddr'], '-I', 'lanplus', '-U',
serverData['username'], '-P',
decrypt(serverData['password'], serverData['salt']),
'chassis', 'power', cmd])
else:
out, err, rc = run_command(
['ipmitool', '-H', serverData['ipaddr'], '-I', 'lanplus', '-P',
decrypt(serverData['password'], serverData['salt']),
'chassis', 'power', cmd])
if rc == 0:
while True:
serverData = get_server_status(serverData)
if 'on' in cmd and 'on' in serverData['status']:
return True
elif 'off' in cmd and 'off' in serverData['status']:
return True
else:
if count == 15:
return False
count += 1
time.sleep(20)
else:
return False # raising exception is handled by the caller
示例8: _has_sudo
def _has_sudo(self, result):
result.value = False
_master, slave = pty.openpty()
os.setsid()
fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
out, err, exit = run_command(['sudo', '-l', '-U', self.user[USER_NAME],
'sudo'])
if exit == 0:
debug("User %s is allowed to run sudo" % self.user[USER_NAME])
# sudo allows a wide range of configurations, such as controlling
# which binaries the user can execute with sudo.
# For now, we will just check whether the user is allowed to run
# any command with sudo.
out, err, exit = run_command(['sudo', '-l', '-U',
self.user[USER_NAME]])
for line in out.split('\n'):
if line and re.search("(ALL)", line):
result.value = True
debug("User %s can run any command with sudo" %
result.value)
return
debug("User %s can only run some commands with sudo" %
self.user[USER_NAME])
else:
debug("User %s is not allowed to run sudo" % self.user[USER_NAME])
示例9: add_lun
def add_lun(adapter, port, lun_id):
"""
Add a LUN to system
:param adapter: HBA adapter id
:param port: Remote port wwpn
:param lun_id: Id of the given LUN
"""
port_dir = '/sys/bus/ccw/drivers/zfcp/' + adapter + '/' + port + '/'
lun_dir = port_dir + lun_id
wok_log.info("Adding LUN, %s", lun_dir)
if os.path.exists(lun_dir):
# LUN already present on the system, nothing to add.
return
else:
try:
with open(port_dir + 'unit_add', "w") as txt_file:
txt_file.write(lun_id)
for _ in range(4):
# Don't wait for udev queue to completely flush.
# Wait for the relavant entry for this LUN is created in sysfs
run_command([udevadm, "settle", "--exit-if-exists=" + lun_dir])
if os.path.exists(lun_dir):
break
except Exception as e:
wok_log.error("Unable to add LUN, %s", lun_dir)
raise OperationFailed("GS390XSTG00003", {'err': e.message})
示例10: _create_dasd_part
def _create_dasd_part(dev, size):
"""
This method creates a DASD partition
:param dev: name of DASD device for creation of partition
:param size: block size
:return:
"""
devname = '/dev/' + dev
device = PDevice(devname)
disk = PDisk(device)
num_parts = len(disk.partitions)
if num_parts == 3:
raise OperationFailed("GINDASDPAR0016E")
def kill_proc(proc, timeout_flag):
try:
parent = psutil.Process(proc.pid)
for child in parent.get_children(recursive=True):
child.kill()
# kill the process after no children is left
proc.kill()
except OSError:
pass
else:
timeout_flag[0] = True
dasd_devs = _get_dasd_names()
if dev not in dasd_devs:
raise NotFoundError("GINDASDPAR0012E", {'name': dev})
p_str = _form_part_str(size)
try:
p1_out = subprocess.Popen(["echo", "-e", "\'", p_str, "\'"],
stdout=subprocess.PIPE)
p2_out = subprocess.Popen(["fdasd", devname], stdin=p1_out.stdout,
stderr=subprocess.PIPE,
stdout=subprocess.PIPE)
p1_out.stdout.close()
timeout = 2.0
timeout_flag = [False]
timer = Timer(timeout, kill_proc, [p2_out, timeout_flag])
timer.setDaemon(True)
timer.start()
out, err = p2_out.communicate()
if timeout_flag[0]:
msg_args = {'cmd': "fdasd " + devname, 'seconds': str(timeout)}
raise TimeoutExpired("WOKUTILS0002E", msg_args)
if p2_out.returncode != 0:
if 'error while rereading partition table' in err.lower():
run_command(["partprobe", devname, "-s"])
else:
raise OperationFailed("GINDASDPAR0007E",
{'name': devname, 'err': err})
except TimeoutExpired:
raise
finally:
if timer and not timeout_flag[0]:
timer.cancel()
示例11: __init__
def __init__(self, **kargs):
self.guest_threads_enabled = False
self.sockets = 0
self.cores_present = 0
self.cores_available = 0
self.cores_per_socket = 0
self.threads_per_core = 0
self.max_threads = 0
self.conn = kargs['conn']
libvirt_topology = None
try:
connect = self.conn.get()
libvirt_topology = get_topo_capabilities(connect)
except Exception as e:
wok_log.info("Unable to get CPU topology capabilities: %s"
% e.message)
return
if libvirt_topology is None:
wok_log.info("cpu_info topology not supported.")
return
if ARCH == 'power':
# IBM PowerPC
self.guest_threads_enabled = True
out, error, rc = run_command(['ppc64_cpu', '--smt'])
if rc or 'on' in out:
# SMT has to be disabled for guest to use threads as CPUs.
# rc is always zero, whether SMT is off or on.
self.guest_threads_enabled = False
out, error, rc = run_command(['ppc64_cpu', '--cores-present'])
if not rc:
self.cores_present = int(out.split()[-1])
out, error, rc = run_command(['ppc64_cpu', '--cores-on'])
if not rc:
self.cores_available = int(out.split()[-1])
out, error, rc = run_command(['ppc64_cpu', '--threads-per-core'])
if not rc:
self.threads_per_core = int(out.split()[-1])
self.sockets = self.cores_present/self.threads_per_core
if self.sockets == 0:
self.sockets = 1
self.cores_per_socket = self.cores_present/self.sockets
else:
# Intel or AMD
self.guest_threads_enabled = True
self.sockets = int(libvirt_topology.get('sockets'))
self.cores_per_socket = int(libvirt_topology.get('cores'))
self.cores_present = self.cores_per_socket * self.sockets
self.cores_available = self.cores_present
self.threads_per_core = int(libvirt_topology.get('threads'))
示例12: create_file
def create_file(self):
fcmd = ["dd", "if=/dev/zero", "of=%s" % TESTFILE,
"bs=10M", "count=1"]
fout, err, rc = run_command(fcmd)
if rc:
self.assertRaises(OperationFailed)
fscmd = ["mkfs.ext4", TESTFILE, "-F"]
fsout, err, rc = run_command(fscmd)
if rc:
self.assertRaises(OperationFailed)
if not os.path.exists(TESTDIR):
os.makedirs(TESTDIR)
示例13: activate_iface
def activate_iface(self, ifacename):
wok_log.info('Bring up an interface ' + ifacename)
iface_type = netinfo.get_interface_type(ifacename)
if iface_type == "nic":
cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
out, error, returncode = run_command(cmd_ipup)
if returncode != 0:
# non-ascii encoded value and unicode value
# cannot be concatenated, so convert both variable
# to one format.
raise OperationFailed('GINNET0059E',
{'name': encode_value(ifacename),
'error': encode_value(error)})
# Some times based on system load, it takes few seconds to
# reflect the /sys/class/net files upon execution of 'ip link
# set' command. Following snippet is to wait util files get
# reflect.
timeout = self.wait_time(ifacename)
if timeout == 5:
wok_log.warn("Time-out has happened upon execution of 'ip "
"link set <interface> up', hence behavior of "
"activating an interface may not as expected.")
else:
wok_log.info('Successfully brought up the interface ' +
ifacename)
wok_log.info('Activating an interface ' + ifacename)
cmd_ifup = ['ifup', ifacename]
out, error, returncode = run_command(cmd_ifup)
# Timeout is used for carrier file
# since the carrier file needs few seconds approx 5 sec
# to update the carrier value of an iface from 0 to 1.
self.wait_time_carrier(ifacename)
# Check for the carrier value after the device is activated
if os.path.isfile(carrier_path % ifacename):
with open(carrier_path % ifacename) as car_file:
carrier_val = car_file.readline().strip()
if (carrier_val == '0'):
if iface_type != "nic":
raise OperationFailed('GINNET0094E', {'name': ifacename})
else:
raise OperationFailed('GINNET0090E', {'name': ifacename})
else:
raise OperationFailed('GINNET0091E', {'name': ifacename})
if returncode != 0:
raise OperationFailed('GINNET0016E',
{'name': encode_value(ifacename),
'error': encode_value(error)})
wok_log.info(
'Connection successfully activated for the interface ' + ifacename)
示例14: activate_iface
def activate_iface(self, ifacename):
wok_log.info('Bring up an interface ' + ifacename)
iface_type = netinfo.get_interface_type(ifacename)
filename = ifcfg_filename_format % ifacename
filepath = os.sep + network_configpath + filename
if os.path.exists(filepath):
if not (os.stat(filepath).st_size == 0):
wok_log.info('Activating an interface ' + ifacename)
cmd_ifup = ['ifup', ifacename]
out, error, returncode = run_command(cmd_ifup)
if (returncode == 4):
raise OperationFailed('GINNET0095E', {'name': ifacename})
# Timeout is used for carrier file
# since the carrier file needs few seconds approx 5 sec
# to update the carrier value of an iface from 0 to 1.
self.wait_time_carrier(ifacename)
# Check for the carrier value after the device is activated
if os.path.isfile(carrier_path % ifacename):
with open(carrier_path % ifacename) as car_file:
carrier_val = car_file.readline().strip()
if (carrier_val == '0'):
if iface_type != "nic":
raise OperationFailed('GINNET0094E',
{'name': ifacename})
else:
raise OperationFailed('GINNET0090E',
{'name': ifacename})
else:
raise OperationFailed('GINNET0091E', {'name': ifacename})
if returncode != 0:
raise OperationFailed('GINNET0016E',
{'name': encode_value(ifacename),
'error': encode_value(error)})
wok_log.info('Connection successfully activated for the '
'interface ' + ifacename)
else:
cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
out, error, returncode = run_command(cmd_ipup)
if returncode != 0:
raise OperationFailed('GINNET0059E', {'name': ifacename})
wok_log.info('Connection successfully activated for the '
'interface ' + ifacename)
else:
cmd_ipup = ['ip', 'link', 'set', '%s' % ifacename, 'up']
out, error, returncode = run_command(cmd_ipup)
if returncode != 0:
raise OperationFailed('GINNET0059E', {'name': ifacename})
wok_log.info('Connection successfully activated for the '
'interface ' + ifacename)
示例15: _validate_pci_passthrough_env
def _validate_pci_passthrough_env():
# Linux kernel < 3.5 doesn't provide /sys/kernel/iommu_groups
if os.path.isdir('/sys/kernel/iommu_groups'):
if not glob.glob('/sys/kernel/iommu_groups/*'):
raise InvalidOperation("KCHVMHDEV0003E")
# Enable virt_use_sysfs on RHEL6 and older distributions
# In recent Fedora, there is no virt_use_sysfs.
out, err, rc = run_command(['getsebool', 'virt_use_sysfs'],
silent=True)
if rc == 0 and out.rstrip('\n') != "virt_use_sysfs --> on":
out, err, rc = run_command(['setsebool', '-P',
'virt_use_sysfs=on'])
if rc != 0:
wok_log.warning("Unable to turn on sebool virt_use_sysfs")