Month: June 2012

Accessing WMI on other machines

Another admin here has been using PowerShell to check services running on a group of servers and restart them if they have stopped. Not wanting to learn PowerShell just for this I decided to have a go at writing the same script in Python.

Again Tim Golden allows the process to be simplified a little with his WMI module. There is a windows installer for this one which hides all the installation.

To access a remote server rather than your local computer just pass the servername as a parameter to the WMI function. A list of services is obtained from Win32_Service() and rest is fairly straight forward.

I created an example script which goes through a list of servers and compares all theĀ  services against a tuple of services I am interested in for any that have stopped. If it finds any it prints out the server number and the service caption before trying to start the server again.

I’ve not bothered with authorisation, the script would need to be run under a user account with the necessary privileges. The script is also not optimised, I might come back to this at a later date.

Tim Golden’s active_directory wrapper in Python 3

Tim Golden wrote a useful wrapper for accessing active directory. It is was written for Python 2 but 2to3.py is able to fully translate it. Once downloaded (and updated to 3 if applicable) run python setup.py install to compile and copy the library ready to be used in your programs.

For example to display the user logon name (ID) for all accounts with a name beginning with quackajack (notice the asterisk to do the wildcard search)

import active_directory
adusers = active_directory.search("displayName='quackajack*'", objectCategory='Person', objectClass='User')
for adu in adusers:
    print adu.sAMAccountName

If using sAMAccountName seems confusing don’t worry. I struggle to remember all but the most common ones preferring to look them up when needed by listing all attributes then picking the ones I need. If you want to have a look a full list of user attributes is available here.

Those who have used dsquery before from the command line may be aware of the using -attr * to display all attributes of the object. You can do the same in your python script with the dump function. Hence changing the print line above to print adu.dump() will print out a key,value list of all attributes. Be warned its a long list.