[python-win32] wmi, Win32_ScheduledJob and Execution User

Mark Hammond mhammond at skippinet.com.au
Fri May 2 03:00:14 CEST 2008


> I've followed Tim Golden's cookbook example to schedule a job via his
> Python wmi module; however, I need to specify the user account a
> scheduled job gets executed under (i.e., the process owner).  The
> cookbook example will schedule a job owned by SYSTEM.  I note the
> actual WMI library provides for a User and Password option, which do
> not appear to be visible options from within the python wmi module's
> Win32_ScheduledJob call.  I am uncertain if the aforementioned User and
> Password options actually cause the scheduled job to be run as that
> user?  As a workaround I schedule my job via the Win32_ScheduledJob
> call and follow this up with a Win32_Process.Create call to
> "schtasks.exe", in which I change the job id's run user (i.e., via the
> /RU option) to the appropriate user name.
> 
> Is there a way I can specify the run (or execution) user of a scheduled
> job within the Win32_ScheduledJob call or via the wmi interface?  The
> way I am doing it right now, I could have simply called schtasks.exe
> directly and had it create the process with the intended run user,
> which I don't find very eloquent.

I'm not sure exactly where you are at, but here is a snippet of code that we
use at Enfold.  Note that 'username' is a string param, and that we have
special handling of '.\\localsystem' that you probably don't.

from win32com.taskscheduler import taskscheduler
ts=pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None,
 
pythoncom.CLSCTX_INPROC_SERVER,taskscheduler.IID_ITaskScheduler)
...
t=ts.NewWorkItem(task_name)
t.SetComment("The comment")
t.SetApplicationName(executable)
...
# Note: Windows 2000 appears to allow the task to be set with an
# incorrect password - it just fails to run. XP SP2+ fails to add the task.
# None password is only valid for local system acct or if task flags contain
TASK_FLAG_RUN_ONLY_IF_LOGGED_ON
# so there is no point defaulting to a the current user - we don't know
their password!
# So we have hard-coded support for ".\LocalSystem" and set the task
accordingly -
# otherwise we need a username and password.
if username.lower() == ".\\localsystem":
    t.SetAccountInformation("", None)
else:
    assert username and password, "Need a username and password!"
    # almost everywhere else allows ".\username" but not here - expand
manually.
    if username.startswith(".\\"):
        username = win32api.GetComputerName() + username[1:]
    t.SetAccountInformation(username, password)
...

Hope that helps,

Mark



More information about the python-win32 mailing list