Skip to content

Commit 1c9d9ea

Browse files
committed
Replace WMIC with powershell cmd
From Win11-24H2, WMIC is an optional feature for Windows, And it will be fully removed in the future.So replace the related cmd Signed-off-by: Leidong Wang <[email protected]>
1 parent 1760004 commit 1c9d9ea

File tree

9 files changed

+101
-49
lines changed

9 files changed

+101
-49
lines changed

virttest/utils_disk.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -835,7 +835,7 @@ def get_disk_size_windows(session, did):
835835
e.g. 0, 1
836836
:return: disk size.
837837
"""
838-
cmd = "wmic diskdrive get size, index"
838+
cmd = 'powershell -command "Get-CimInstance Win32_DiskDrive | Select-Object Index, Size"'
839839
return int(re.findall(r"%s\s+(\d+)" % did, session.cmd_output(cmd))[0])
840840

841841

virttest/utils_misc.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2351,8 +2351,7 @@ def get_free_disk(session, mount):
23512351
:return string: freespace M-bytes
23522352
"""
23532353
if re.match(r"[a-zA-Z]:", mount):
2354-
cmd = "wmic logicaldisk where \"DeviceID='%s'\" " % mount
2355-
cmd += "get FreeSpace"
2354+
cmd = ('powershell -command "Get-CimInstance Win32_LogicalDisk | Where-Object {$_.DeviceID -eq \'%s\'} | Select-Object FreeSpace"') % mount
23562355
output = session.cmd_output(cmd)
23572356
free = "%sK" % re.findall(r"\d+", output)[0]
23582357
else:
@@ -2375,7 +2374,8 @@ def get_free_mem(session, os_type):
23752374
if os_type != "windows":
23762375
free = "%s kB" % get_mem_info(session, "MemFree")
23772376
else:
2378-
output = session.cmd_output("wmic OS get FreePhysicalMemory")
2377+
output = session.cmd_output('powershell -command "Get-CimInstance Win32_OperatingSystem | '
2378+
'Select-Object FreePhysicalMemory"')
23792379
free = "%sK" % re.findall("\d+", output)[0]
23802380
free = float(normalize_data_size(free, order_magnitude="M"))
23812381
return int(free)
@@ -2475,11 +2475,12 @@ def get_win_disk_vol(session, condition="VolumeName='WIN_UTILS'"):
24752475
Getting logicaldisk drive letter in windows guest.
24762476
24772477
:param session: session Object.
2478-
:param condition: supported condition via cmd "wmic logicaldisk list".
2478+
:param condition: supported condition via powershell cmd "Get-CimInstance Win32_LogicalDisk".
24792479
24802480
:return: volume ID.
24812481
"""
2482-
cmd = "wmic logicaldisk where (%s) get DeviceID" % condition
2482+
c_name, c_value = condition.split('=')
2483+
cmd = ('powershell -command "Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object {$_.%s -like %s} | Select-Object DeviceID"') % (c_name, c_value)
24832484
output = session.cmd(cmd, timeout=120)
24842485
device = re.search(r"(\w):", output, re.M)
24852486
if not device:

virttest/utils_net.py

Lines changed: 33 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1654,10 +1654,12 @@ def set_guest_ip_addr(session, mac, ip_addr, netmask="255.255.255.0", os_type="l
16541654
session.cmd(cmd, timeout=360)
16551655
elif os_type == "windows":
16561656
info_cmd = "ipconfig /all"
1657-
cmd = (
1658-
"wmic nicconfig where MACAddress='%s' call "
1659-
"enablestatic '%s','%s'" % (mac, ip_addr, netmask)
1660-
)
1657+
get_nic_cmd = ('powershell -command "$Adapter=Get-CimInstance Win32_NetworkAdapterConfiguration | '
1658+
'Where-Object {$_.MACAddress -eq \'%s\'}; $Adapter.InterfaceIndex') % mac
1659+
nic_index = session.cmd_output(get_nic_cmd, timeout=120)
1660+
prefix_length = subnet_mask_to_prefix_length(netmask)
1661+
cmd = ('powershell -command "New-NetIPAddress -InterfaceIndex %s -IPAddress \'%s\' -PrefixLength %s"' %
1662+
(nic_index, ip_addr, prefix_length))
16611663
session.cmd(cmd, timeout=360)
16621664
else:
16631665
info_cmd = ""
@@ -1666,6 +1668,23 @@ def set_guest_ip_addr(session, mac, ip_addr, netmask="255.255.255.0", os_type="l
16661668
LOG.debug(session.cmd_output(info_cmd))
16671669
raise IPAddrSetError(mac, ip_addr, err)
16681670

1671+
def subnet_mask_to_prefix_length(subnet_mask):
1672+
"""
1673+
Convert subnet_mask from 255.*** to prefix length
1674+
1675+
:param subnet_mask: nic subnet_mask
1676+
1677+
:return: prefix length
1678+
"""
1679+
1680+
octets = subnet_mask.split('.')
1681+
1682+
prefix_length = 0
1683+
for octet in octets:
1684+
prefix_length += bin(int(octet)).count('1')
1685+
1686+
return prefix_length
1687+
16691688

16701689
def get_guest_nameserver(session):
16711690
"""
@@ -3788,7 +3807,8 @@ def str2ipaddr(str_ip):
37883807
return None
37893808

37903809
maps = {}
3791-
cmd = "wmic nicconfig where IPEnabled=True get ipaddress, macaddress"
3810+
cmd = ('powershell -command "Get-CimInstance Win32_NetworkAdapterConfiguration | '
3811+
'Where-Object {$_.IPEnabled -eq \'True\'} | Select-Object IPAddress, MACAddress"')
37923812
out = session.cmd_output(cmd)
37933813
regex = r".*\w{2}[:-]\w{2}[:-]\w{2}[:-]\w{2}[:-]\w{2}[:-]\w{2}\s*"
37943814
lines = [l.strip() for l in out.splitlines() if l.strip()]
@@ -3941,19 +3961,20 @@ def update_mac_ip_address(vm, timeout=240):
39413961

39423962

39433963
def get_windows_nic_attribute(
3944-
session, key, value, target, timeout=240, global_switch="nic"
3964+
session, key, value, target, timeout=240, global_switch="NetworkAdapter"
39453965
):
39463966
"""
3947-
Get the windows nic attribute using wmic. All the support key you can
3948-
using wmic to have a check.
3967+
Get the windows nic attribute using powershell. All the support key you can
3968+
using powershell to have a check.
39493969
39503970
:param session: session to the virtual machine
3951-
:param key: the key supported by wmic
3971+
:param key: the key supported by Get-CimInstance
39523972
:param value: the value of the key
39533973
:param target: which nic attribute you want to get.
39543974
39553975
"""
3956-
cmd = 'wmic %s where %s="%s" get %s' % (global_switch, key, value, target)
3976+
cmd = ('powershell -command "Get-CimInstance Win32_%s | Where-Object {$_.%s -eq \'%s\'} | Select-Object %s"'
3977+
% (global_switch, key, value, target))
39573978
status, out = session.cmd_status_output(cmd, timeout=timeout)
39583979
if status != 0:
39593980
err_msg = "Execute guest shell command('%s') " "failed with error: '%s'" % (
@@ -3993,7 +4014,7 @@ def restart_windows_guest_network(session, connection_id, timeout=240, mode="net
39934014
39944015
:param session: session to virtual machine
39954016
:param connection_id: windows nic connectionid,it means connection name,
3996-
you Can get connection id string via wmic
4017+
you Can get connection id string via wmic or powershell
39974018
"""
39984019
if mode == "netsh":
39994020
disable_windows_guest_network(session, connection_id, timeout=timeout)
@@ -4011,7 +4032,7 @@ def restart_windows_guest_network_by_key(
40114032
using devcon mode must download devcon.exe and put it under c:\
40124033
40134034
:param session: session to virtual machine
4014-
:param key: the key supported by wmic nic
4035+
:param key: the key supported by Get-CimInstance nic
40154036
:param value: the value of the key
40164037
:param timeout: timeout
40174038
:param mode: command mode netsh or devcon

virttest/utils_netperf.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,7 @@ def __init__(
290290
def is_target_running(self, target):
291291
list_cmd = "ps -C %s" % target
292292
if self.client == "nc":
293-
list_cmd = "wmic process where name='%s' list" % target
293+
list_cmd = 'powershell -command "Get-CimInstance Win32_Process | Where-Object {$_.Name -eq \'%s\'} | Format-List *"' % target
294294
try:
295295
output = self.session.cmd_output_safe(list_cmd, timeout=120)
296296
check_reg = re.compile(r"%s" % target, re.I | re.M)

virttest/utils_test/__init__.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -300,18 +300,19 @@ def start_windows_service(session, service, timeout=120):
300300

301301
def get_windows_file_abs_path(session, filename, extension="exe", tmout=240):
302302
"""
303-
return file abs path "drive+path" by "wmic datafile"
303+
return file abs path "drive+path" by Get-CimInstance
304304
"""
305-
cmd_tmp = "wmic datafile where \"Filename='%s' and "
306-
cmd_tmp += "extension='%s'\" get drive^,path"
307-
cmd = cmd_tmp % (filename, extension)
305+
full_name = filename + '.' + extension
306+
cmd = ('powershell -command "Get-PSDrive -PSProvider FileSystem | ForEach-Object '
307+
'{Get-ChildItem -Path $_.Root -Filter \"%s\" -Recurse -ErrorAction SilentlyContinue} |'
308+
' Select-Object Fullname"') % full_name
308309
info = session.cmd_output(cmd, timeout=tmout).strip()
309-
drive_path = re.search(r"(\w):\s+(\S+)", info, re.M)
310-
if not drive_path:
310+
file_abs_path = re.search(r"^[A-Z]:\\.*\.*$", info, re.M)
311+
if not file_abs_path:
311312
raise exceptions.TestError(
312313
"Not found file %s.%s in your guest" % (filename, extension)
313314
)
314-
return ":".join(drive_path.groups())
315+
return file_abs_path.string
315316

316317

317318
def get_windows_disk_drive(session, filename, extension="exe", tmout=240):

virttest/utils_test/qemu/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -488,7 +488,7 @@ def get_guest_total_mem(cls, vm):
488488
:return: physical memory report by guest OS in MB
489489
"""
490490
if vm.params.get("os_type") == "windows":
491-
cmd = "wmic ComputerSystem get TotalPhysicalMemory"
491+
cmd = 'powershell -command "(Get-CimInstance -ClassName Win32_ComputerSystem).TotalPhysicalMemory"'
492492
else:
493493
cmd = "grep 'MemTotal:' /proc/meminfo"
494494
return vm.get_memory_size(cmd)

virttest/utils_windows/drive.py

Lines changed: 34 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,30 @@
11
"""
22
Windows drive utilities
33
"""
4+
import re
45

56
from virttest import utils_misc
67

78
from . import wmic
89

910

1011
def _logical_disks(session, cond=None, props=None):
11-
cmd = wmic.make_query("LogicalDisk", cond, props, get_swch=wmic.FMT_TYPE_LIST)
12-
out = utils_misc.wait_for(
13-
lambda: wmic.parse_list(session.cmd(cmd, timeout=120)), 240
14-
)
15-
return out if out else []
12+
c_name, c_value = cond.split('=')
13+
cmd = ('powershell -command "Get-CimInstance -ClassName Win32_LogicalDisk | Where-Object {$_.%s -like %s}'
14+
' | Select-Object %s | Format-List *"') % (c_name, c_value, ','.join(props))
15+
out = session.cmd(cmd, timeout=120)
16+
results = []
17+
for para in re.split("(?:\r?\n){2,}", out.strip()):
18+
keys, vals = [], []
19+
for line in para.splitlines():
20+
key, val = line.split(":", 1)
21+
keys.append(key.strip())
22+
vals.append(val.strip())
23+
if len(keys) == 1:
24+
results.append(vals[0])
25+
else:
26+
results.append(dict(zip(keys, vals)))
27+
return results if results else []
1628

1729

1830
def get_hard_drive_letter(session, label):
@@ -24,7 +36,7 @@ def get_hard_drive_letter(session, label):
2436
2537
:return: Hard drive's letter if found, otherwise `None`.
2638
"""
27-
cond = "VolumeName like '%s'" % label
39+
cond = "VolumeName='%s'" % label
2840
try:
2941
return _logical_disks(session, cond=cond, props=["DeviceID"])[0]
3042
except IndexError:
@@ -103,13 +115,19 @@ def get_disk_props_by_serial_number(session, serial_number, props):
103115
:return: The mapping between properties and values.
104116
:rtype: dict
105117
"""
106-
cond = "SerialNumber like '%s'" % serial_number
107-
cmd = wmic.make_query("diskdrive", cond, props=props, get_swch=wmic.FMT_TYPE_LIST)
108-
out = wmic.parse_list(session.cmd(cmd, timeout=120))
109-
110-
if out:
111-
mapping = out[-1]
112-
if isinstance(mapping, str):
113-
return {props[0]: mapping}
114-
return mapping
115-
return {}
118+
cmd = ('powershell -command "Get-CimInstance -ClassName Win32_Diskdrive | Where-Object {$_.SerialNumber -eq %s}'
119+
' | Select-Object %s | Format-List *"') % (serial_number, ','.join(props))
120+
out = session.cmd(cmd, timeout=120)
121+
results = []
122+
for para in re.split("(?:\r?\n){2,}", out.strip()):
123+
print(para)
124+
keys, vals = [], []
125+
for line in para.splitlines():
126+
key, val = line.split(":", 1)
127+
keys.append(key.strip())
128+
vals.append(val.strip())
129+
if len(keys) == 1:
130+
results.append(vals[0])
131+
else:
132+
results.append(dict(zip(keys, vals)))
133+
return results if results else []

virttest/utils_windows/system.py

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,27 @@
11
"""
22
Windows system utilities
33
"""
4+
import re
45

56
from . import wmic
67

78

89
def _osinfo(session, props=None):
9-
cmd = wmic.make_query("os", props=props, get_swch=wmic.FMT_TYPE_LIST)
10-
try:
11-
return wmic.parse_list(session.cmd(cmd))[0]
12-
except IndexError:
13-
return None
10+
cmd = ('powershell -command "Get-CimInstance -ClassName Win32_OperatingSystem | Select-Object %s | Format-List *"'
11+
% (','.join(props)))
12+
out = session.cmd(cmd, timeout=120)
13+
results = []
14+
for para in re.split("(?:\r?\n){2,}", out.strip()):
15+
keys, vals = [], []
16+
for line in para.splitlines():
17+
key, val = line.split(":", 1)
18+
keys.append(key.strip())
19+
vals.append(val.strip())
20+
if len(keys) == 1:
21+
results.append(vals[0])
22+
else:
23+
results.append(dict(zip(keys, vals)))
24+
return results[0] if results else []
1425

1526

1627
def product_name(session):

virttest/utils_windows/virtio_win.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def drive_letter_iso(session):
101101
102102
:return: Drive letter.
103103
"""
104-
return drive.get_hard_drive_letter(session, "virtio-win%")
104+
return drive.get_hard_drive_letter(session, "virtio-win*")
105105

106106

107107
def drive_letter_vfd(session):

0 commit comments

Comments
 (0)