Sometime back we had a requirement of running an exe in the context of network user. Initially it looked very easy. But when I tried to impersonate the execution, I realized the difficulty. It is easy to impersonate as a standard user .But cannot impersonate as NetworkService. So what are the alternatives.
- Run a windows service and start the process/executable from that service.
- Schedule a task and specify target as our exe and use NetworkService to initiate execution. Delete the task after execution.
Run exe through windows service
This is a simple matter or creating a windows service and executing a exe when we start the service. Immediately after completion of exe stop the service.This can be summarized as
- Create a simple windows service
- This should accept an exe path through the OnStart() method.
- Execute the exe.
- Stop the service by calling Stop() method.
- Use the sc start command to start the service and pass path as param.
You may download the program from here.
Schedule task on behalf of NetworkService
This too simple. The steps are
- Create a scheduled task pointing to your application using ‘schtasks’ command.
- Use “NT AUTHORITY\NETWORK SERVICE" as user profile
- Give the run frequency as onlogon. This is to ensure that, it will never run before we trigger.
- eg: <drive>:\<folder>>schtasks /create /tn testser /sc onlogon /ru "NT AUTHORITY\NETWORK SERVICE" /tr d:\Temp\HelloWorld.exe (No way to reduce params)
- Run the task
- schtasks /run /tn "testser"
- Delete the task
- schtasks /delete /tn testser /f (/f is to delete forcefully.Else it will ask a confirmation)
Better wrap this into a single batch file which accepts the exe name and run the same in the context of ‘NetworkService’. ie you can use like RunAsNetworkService <file path>
NB: If you simply create the task using command, it will not run, it is in a portable system such as laptop and it is in battery during invocation. To resolve that, you need to create an xml file where you can specify to enable task running in batteries and point the same xml in the task creation command.Below links explains how to create task with xml file option.