Search code examples
pythonwmifilesystemobject

Unable to create file system object in wmi using python


I connected to remote windows server using wmi. I want to create filesystem object to extract file version of file on remote server.

My code goes like this:

# mc_name-machine name, login_machine() to login
c = login_machine(mc_name) 
print "logged-in"
# erroneous line. 
fo = c.win32com.client.Dispatch('Scripting.filesystemobject') 
# path=path of file on remote machine
print fo.GetFileVersion(path)

Help will be greatly appreciated.

For the erroneous line in above code error thrown:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\wmi.py", line 1145, in __getattr__
    return self._cached_classes (attribute)
  File "C:\Python34\lib\site-packages\wmi.py", line 1156, in _cached_classes
    self._classes_map[class_name] = _wmi_class (self, self._namespace.Get (class_name))
  File "<COMObject <unknown>>", line 3, in Get
  File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 282, in _ApplyTypes_
    result = self._oleobj_.InvokeTypes(*(dispid, LCID, wFlags, retType, argTypes) + args)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'SWbemServicesEx', 'Not found ', None, 0, -2147217406), None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<pyshell#54>", line 1, in <module>
    fo=c.win32com.client.Dispatch('Scripting.filesystemobject')
  File "C:\Python34\lib\site-packages\wmi.py", line 1147, in __getattr__
    return getattr (self._namespace, attribute)
  File "C:\Python34\lib\site-packages\win32com\client\dynamic.py", line 522, in __getattr__
    raise AttributeError("%s.%s" % (self._username_, attr))
AttributeError: <unknown>.win32com

I was trying to solve this by using ProvideConstants. Code for same

fo = win32com.client.Dispatch('Scripting.filesystemobject')
foo=ProvideConstants(fo)

I'm not sure how to use this wmi.ProvideConstants object to get file version.


Solution

  • I was able to query the version of a remote file with this code:

    c = wmi.WMI('computer', user='domain\\user', password='pass')
    result = c.query('SELECT * FROM CIM_DataFile WHERE Name = "C:\\path\to\file"')
    for file in result:
        print file.Version
    

    Update: To get the LastModifed time as a python datetime object, and print it out in dd/mm/yyyy format:

    from datetime import datetime
    last_modified = datetime(*wmi.to_time(file.LastModified)[:7])
    print last_modified.strftime("%d/%m/%Y")