【问题标题】:accesing WMI information from python从 python 访问 WMI 信息
【发布时间】:2014-05-22 18:30:02
【问题描述】:

我有这个小的 PS 脚本,它为 iSCSI 启动器输出一个 IP 地址列表和它们各自的 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)>

希望对这方面有一定了解的人能不吝赐教

【问题讨论】:

    标签: python powershell wmi iscsi


    【解决方案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 保存为数字而不格式化...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 2020-05-09
      • 1970-01-01
      • 2018-11-13
      • 2011-05-06
      相关资源
      最近更新 更多