我有这个小PS脚本,它输出一个ip地址列表及其各自的iSCSI发起者ID。现在我想用这些信息做更广泛的事情,因为我不太了解PS及其工作方式,我想将脚本迁移到python并从那里继续。
现在PS脚本通过WMI获取这些内容。这是:
function Get-IscsiPortNumber {
$PortalSummary = @()
$portalInfo = get-wmiobject -namespace root\wmi -class msiscsi_portalinfoclass
$eScriptBlock ={([Net.IPAddress]$_.ipaddr.IPV4Address).IPAddressToString}
$customLabel = @{Label="IpAddress"; expression = $eScriptBlock}
foreach ($portal in $portalInfo) {
foreach ($p in ($portal.portalinformation)) {
$CurrentPort = New-Object PsObject -Property @{ `
NetID = $p.port;`
IP = ([net.ipaddress]$p.ipaddr.IpV4Address).IPAddressToString `
}
$PortalSummary += $CurrentPort
}
}
return $PortalSummary
}
Get-IscsiPortNumber | ft -AutoSize
在python中我开始做这样的事情,但我在运行时总是遇到错误:
import wmi
test = wmi.WMI(namespace='root\wmi',moniker='msiscsi_portalinfoclass')
说:
Traceback (most recent call last):
File "C:\Users\rg\Desktop\diskchecktptest\getnicids.py", line 2, in <module>
test = wmi.WMI(namespace='root\wmi',moniker='msiscsi_portalinfoclass')
File "C:\Python27\lib\site-packages\wmi.py", line 1290, in connect
handle_com_error ()
File "C:\Python27\lib\site-packages\wmi.py", line 241, in handle_com_error
raise klass (com_error=err)
wmi.x_wmi: <x_wmi: Unexpected COM Error (-2147217406, 'OLE error 0x80041002', No
ne, None)>
我希望有一些关于这个主题的知识的人能够启发我
答案 0 :(得分:1)
我明白了。
from win32com.client import GetObject
def Int2IP(ipnum):
o1 = int(ipnum / 16777216) % 256
o2 = int(ipnum / 65536) % 256
o3 = int(ipnum / 256) % 256
o4 = int(ipnum) % 256
return '%(o4)s.%(o3)s.%(o2)s.%(o1)s' % locals()
objWMI = GetObject('winmgmts:\\\\.\\root\\WMI').InstancesOf('MSiSCSI_PortalInfoClass')
for obj in objWMI:
for p in obj.PortalInformation:
print str(p.port) + ' | ' + Int2IP(p.ipaddr.IpV4Address) + '\n')
虽然它将ip保存为没有格式化的数字而非常奇怪......