0

Trying to run a bat file from a windows service. Here is the code:

try
            {
                SecureString securePwd = new SecureString();
                foreach (char c in pwd)
                {
                    securePwd.AppendChar(c);
                }
                Process process = new Process();
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.FileName = @"CMD.exe";  //The file in that DIR.
                process.StartInfo.WorkingDirectory = @"C:\";
                process.StartInfo.Arguments = @"/C " + filePath;
                process.StartInfo.Verb = "runas";
                process.StartInfo.UserName = user;
                process.StartInfo.Password = securePwd;
                process.Start();
            }
            catch (Exception ex)
            {
                EventLog myEventLog = new EventLog { Source = "MoC LaneUpdate" };
                myEventLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);
            }

I have verified that this same code works when running in a non-service. I am also not getting an error message, however the .bat file does not run, at least it does not appear to in my current user session. Is my file running in a background session? How can I run a batch file in the user specified in the startinfo?

user3839756
  • 793
  • 1
  • 9
  • 22
  • 1
    _"it does not appear to in my current user session"_ -- sounds normal to me, assuming you're actually running the service code as a service. Running under a different user's credentials doesn't change the fact that there's no login session in which to show a console window, just as when you run a program "as administrator" in your own login session, that program still uses your session for its user interface. What evidence do you have that the batch file is not actually executed? What makes you think the code you posted should be doing anything other than what it is doing? – Peter Duniho Aug 23 '16 at 00:36
  • Right, but the task the my batch file is supposed to complete is never completed. Im not worried about not seeing the cmd prompt. – user3839756 Aug 23 '16 at 00:37
  • You can configure the service to allow interaction with the desktop. After the service has been installed, go to the services screen and the log on tab of the properties menu for the service. check the box Allow service to interact with desktop. – Dave Greilach Aug 23 '16 at 00:38
  • 1
    Oh. Your code looks good then. Just for funsies, can you write a bat file that will create a text file that will leave you concrete evidence if it is being called or not? Then if you have your service call that you'll know for sure it's working to call a bat file. – Dave Greilach Aug 23 '16 at 00:40
  • @David: re: your suggestion to enable interaction with the desktop: http://stackoverflow.com/a/4237283. – Peter Duniho Aug 23 '16 at 00:44
  • @PeterDuniho makes sense. I haven't actually seen that used since we tried to hack something together on an XP machine for a quick fix. – Dave Greilach Aug 23 '16 at 00:55
  • 1
    So far, the only definite statement you've made about the execution of your batch file is that _"it does not appear to in my current user session"_. As I've said, this is normal and so the statement doesn't represent any sort of problem statement. Please improve the question so that you have an actual problem statement; confirm that the batch file does in fact not run, and then edit the question so that you've provided a good [mcve] that reliably reproduces that problem. – Peter Duniho Aug 23 '16 at 01:03
  • The problem is (almost certainly) that the user account doesn't have the necessary rights to run on the service's desktop and window station. Something like [this](https://msdn.microsoft.com/en-us/library/aa379608(VS.85).aspx) may be necessary (assuming the suggestion in the posted answer doesn't work) but it would be a lot of work to port that to C#. – Harry Johnston Aug 23 '16 at 01:37
  • Incidentally, by doing this you're exposing the system to potential elevation-of-privilege attacks by the user account you're running the batch file as. (If it's an admin account, that doesn't matter. If it is a non-admin account, you need to consider whether this is a sensible thing to do.) – Harry Johnston Aug 23 '16 at 01:45
  • Since the answer that might (or, admittedly, might not) have provided a simple resolution to your problem has now been deleted, see [this question](http://stackoverflow.com/q/1556852/886887). – Harry Johnston Aug 23 '16 at 22:24

1 Answers1

0

For a windows service run a desktop application is necessary the service create a user process.

Services are created in session 0, where is not allowed graphical interface they are not displayed, being necessary create a process in section the user is logged in (other than 0).

For this is necessary to use resources of the windows api.

Following example in vb.net.

ps: sorry for my English.

 Try

        Dim UserTokenHandle As IntPtr = IntPtr.Zero
        Dim ProcInfo As New WindowsApi.PROCESS_INFORMATION
        Dim StartInfo As New WindowsApi.STARTUPINFOW

        'obtain an access token(handle) for the session that the user logged in is using.
        WindowsApi.WTSQueryUserToken(WindowsApi.WTSGetActiveConsoleSessionId, UserTokenHandle)

        'widows specification for the process that will be created
        StartInfo.cb = CUInt(Runtime.InteropServices.Marshal.SizeOf(StartInfo))

        'create a new process to run on the user session represented by UserTokenHandle that was obtained in WTSQueryUserToken
        WindowsApi.CreateProcessAsUser(UserTokenHandle,"C:\FILE_TO_RUN.EXE", IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, False, 0, IntPtr.Zero, Nothing, StartInfo, ProcInfo)

        'checks whether the UserTokenHandle is nonzero
        If Not UserTokenHandle = IntPtr.Zero Then
            WindowsApi.CloseHandle(UserTokenHandle)
        End If

    Catch ex As Exception
       throw
    End Try

References: https://www.2brightsparks.com/resources/articles/understanding-windows-sessions.pdf

http://blogs.technet.com/b/askperf/archive/2007/04/27/application-compatibility-session-0-isolation.aspx

Diogo Rodrigues
  • 1,312
  • 15
  • 15
  • It is no reason an answer be negative for a word mistranslated. instead it might have suggested a better translation. Why not suggest a fix to the code? Wait, the code works, but you knew that. Again, sorry for my English. – Diogo Rodrigues Aug 24 '16 at 02:19
  • 1
    Sorry. I thought you were attempting to explain why the batch file didn't run, I didn't realize that you'd misinterpreted the question. Unfortunately, your code won't do what the OP wants - the batch file has to run as a particular user, your code will run it as whatever user is logged on interactively. (And won't work at all if no user is logged on.) – Harry Johnston Aug 24 '16 at 03:43