Random ...
 
December 2017
S M T W T F S
          1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31            
Tags ...
Links



python+zope++:: Pushing ahead with python and wmi
Posted at 08.Mar,2005 12:46  Comments 0 / Trackbacks 0 / Like this post!
Technorati tag(s):
Finally, I went ahead and tried coding something that resembles an asset manager using WMI, Tim's python wmi wrapper, MS access, and zope.

The grand plan was to get all (most) information that's available from windows 2000 and above. It was a good plan. The execution is something else :P.

I have a script that:
- pings a host
- if it's alive, create a wmi instance of that host
- get all necessary information.
- insert information into ms access (for this prototype)
- write to text file for information that requires more than 255 chars (MS access limitation)
- close and commit
-repeat

Disclaimer before I put up my amateurish code: This works for me, ymmv and all that stuff.

The codes are GPL2. Also, please mail me if you do use it and feedback all changes.

I decided to put the codes up for peer review, so that I can learn and be better.

Putting stuff in a dict seemed a bit klunky., so I stored all information in class instance attributes. Is that the way to go? Is there a better and easy way?

Connecting from zope is easy. Just create a ZODBC connection, and create all necessary sqlmethod.

For my quick hack, I created two ZSQLMethods, and used Z Search Interface for a quick and dirty (and functional) web page.

I postponed the Zope Product to some time later since RDB works ok.

Here's the output from help(assMgr) and source.

And here's the main script that I run to get all information.

Help (assMgr) output

>>> import assMgr
>>> help(assMgr)
Help on module assMgr:

NAME
assMgr - #my class

FILE
c:\documents and settings\bak\desktop\assmgr\assmgr.py

CLASSES
assMgr

class assMgr
| Methods defined here:
|
| __init__(self)
| initial attribute is the time the instance created
|
| closeCursor(self, c)
| close cursor
|
| commitDB(self)
| commit the transactions
|
| connect(self, host, username, password)
| connect to said host. another way is to use
| c=wmi.WMI(wmi=wmi.connect_server(server='192.168.130.9',
user='administrator',password='password'))
|
| createFile(self, filelocation)
| create files for process and service; currently a hack since access can
| only cater for 255 chars
|
| getComputerProcess(self, h)
| get info from Win32_Process
|
| getComputerService(self, h)
| get info from Win32_Service
|
| getComputerSystemProductProperties(self, h)
| get information from Win32_ComputerSystemProduct
|
| getCursor(self, dbname)
| helper method to select/test
|
| getOperatingSystemProperties(self, h)
| get info from Win32_OperatingSystem
|
| insertComputerSystemProduct(self, c)
| insert into table
|
| insertOperatingSystem(self, c)
| insert into table
|
| insertServiceProcess(self, c)
| insert into table
|
| pingHost(self, host)
| ping the host once. uses ping.py from mdc
|
| selectComputerSystemProduct(self, c)
| helper method to select/test
|
| selectOperatingSystem(self, c)
| helper method to select/test



Main script



import assMgr

hosts=[]
for i in xrange(1,255):
hosts.append('192.168.105.'+str(i))

logf=open('c:\\temp\\assmgr.log','a')
for host in hosts:
x=assMgr.assMgr()
print 'pinging',host
res=x.pingHost(host)
if res is not None:
try:
print 'trying to connect to',host
h=x.connect(host,'administrator','password')
connstatus = 'ok'
except:
print 'bypassing', host
logf.write('host %s failed\n' % host)
connstatus='ko'
if connstatus=='ok':
print "getting information from ",host
c=x.getCursor('assmgr')
x.getComputerSystemProductProperties(h)
x.getOperatingSystemProperties(h)
x.getComputerProcess(h)
x.getComputerService(h)
try:
x.insertComputerSystemProduct(c)
except:pass
x.insertOperatingSystem(c)
x.closeCursor(c)
x.commitDB()
x.createFile('c:\\temp\\')
logf.write('host %s logged\n' % host)
logf.flush()
print 'done with',host
#logf.close()



Source



#my class
import win32com, wmi, mx.ODBC, mx.ODBC.Windows, time
import ping

class assMgr:
def __init__(self):
"""initial attribute is the time the instance created"""
self.created=str(time.ctime(time.time()))

def pingHost(self,host):
"""ping the host once. uses ping.py from mdc"""
res=ping.doOne(host,2)
return res

def connect(self, host, username, password):
"""connect to said host. another way is to use
c=wmi.WMI(wmi=wmi.connect_server(server='192.168.130.9',
user='administrator',password='password'))
"""
loc=win32com.client.Dispatch("WbemScripting.SWbemLocator")
svc=loc.ConnectServer(host,strUser=username,strPassword=password)
h=wmi.WMI(wmi=svc)
return h

def getComputerSystemProductProperties(self,h):
"""get information from Win32_ComputerSystemProduct"""
for i in h.Win32_ComputerSystemProduct():
self.uuid=str(i.UUID)
self.name=i.Name
self.vendor=i.Vendor

def getComputerProcess(self,h):
"""get info from Win32_Process"""
computerprocess=[]
try:
for i in h.Win32_Process():
p='servicename\t'+str(i.Name)+'::executablepath\t'+str(i.ExecutablePath)+'\n'
computerprocess.append(p)
except:
pass
self.computerprocess=''.join(computerprocess)

def getComputerService(self,h):
"""get info from Win32_Service"""
computerservice=[]
try:
for i in h.Win32_Service():
p='processname\t'+str(i.Name)+'::status\t'+str(i.Status) +'::state\t'+ str(i.State)+'\n'
computerservice.append(p)
except:
pass
self.computerservice=''.join(computerservice)

def getOperatingSystemProperties(self,h):
"""get info from Win32_OperatingSystem"""
for i in h.Win32_OperatingSystem():
self.bootdevice=i.BootDevice
self.buildnumber=i.BuildNumber
self.caption=i.Caption
self.codeset=i.CodeSet
self.countrycode=i.CountryCode
self.csdversion=i.CSDVersion
self.csname=i.CSName
self.installdate=i.InstallDate
self.localdatetime=i.LocalDateTime
self.numberofprocesses=i.NumberOfProcesses
self.numberofusers=i.NumberOfUsers
self.ostype=i.OSType
self.registereduser=i.RegisteredUser
self.serialnumber=i.SerialNumber
self.servicepackmajorversion=i.ServicePackMajorVersion
self.servicepackminorversion=i.ServicePackMinorVersion
self.status=i.Status
self.systemdevice=i.SystemDevice
self.systemdirectory=i.SystemDirectory
self.version=i.Version
self.windowsdirectory=i.WindowsDirectory


def createFile(self,filelocation):
"""create files for process and service;
currently a hack since access can
only cater for 255 chars"""
ext=time.strftime('%Y%m%d%S')
f=open(filelocation+self.uuid+'.'+ext,'w')
f.write(self.computerprocess+'***'+self.computerservice)
f.close()

def selectComputerSystemProduct(self,c):
"""helper method to select/test"""
sqlq="select * from computersystemproduct"
c.execute(sqlq)

def selectOperatingSystem(self,c):
"""helper method to select/test"""
sqlq="select * from operatingsystem"
c.execute(sqlq)

def getCursor(self,dbname):
"""helper method to select/test"""
self.db=mx.ODBC.Windows.connect(dbname)
c=self.db.cursor()
return c

def closeCursor(self,c):
"""close cursor"""
c.close()

def commitDB(self):
"""commit the transactions"""
self.db.commit()



Bookmark and Share

Is this entry helpful? Comments/Donate/Click some google ads.  
Trackback is http://myzope.kedai.com.my/blogs/kedai/16/tbping 

Comments
Post a comment