accesing WMI information from python

1

I have this small PS script which outputs a list of ip adresses and their respective ID's for the iSCSI initiator. Now I want to do some more extensive stuff with this information and since I don't really know PS and the way it works I would like to migrate the script to python and continue from there.

Now the PS script obtains these via the WMI. Here it is:

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

in python I started to do something like this but I always get errors while running it:

import wmi
test = wmi.WMI(namespace='root\wmi',moniker='msiscsi_portalinfoclass')

which say:

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)>

I hope somebody with some knowledge on this subject can enlighten me

python
powershell
wmi
iscsi
asked on Stack Overflow May 22, 2014 by John Smith

1 Answer

1

I figured it out.

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')

its quite odd though that it saves the ip as a number without formatting...

answered on Stack Overflow May 23, 2014 by John Smith

User contributions licensed under CC BY-SA 3.0