How to change the username and password of a windows service using WMI in python

Sometimes it is really hard to find information on the internet. After following instructions from countless blogs and microsoft pages, even trying using the raw WMI API I could not change my service username from “localsystem” to a domain username. Calling the Win32_Server.Change method would return Error 22 – “Status Invalid Parameter”, which was not helpful! Even more frustrating was that when manually changing the service to the new username under Administrative Tools -> services it would work fine. The problem, it turned out, was that when the service was running under local system the checkbox to allow the service to interact with the desktop was checked. This is not allowed when running under an account other than local system and had to be turned off as part of the change call. The second criteria is that under windows 2008 (and above I assume) the user must be given rights to log on as service on the local machine. 

Here is the python code to change a windows service to run under a domain username. Make sure the username has log on as service rights first:

import wmi
#Get a list of services
c = wmi.WMI()
services = c.Win32_Service()
#Find services with a matching prefix (you can change this to find the list of services you want by some other criteria
for service in services:
 if service.Caption.startswith('My_Prefix_'):
 newstartname = r'my_domain\my_username'
 newpassword = r'mypassword'
 result = service.Change(StartMode = 'Automatic',
  DesktopInteract = False,
  StartName = newstartname,
  StartPassword = newpassword)
 print 'Result of attempt to change username to %s: %s' % (newstartname, result)