Create a Windows Session from a service via the Win32 API

后端 未结 4 486
情深已故
情深已故 2021-01-01 03:40

I have a windows service that can create an executable in the users windows session, via calling the \"CreateProcessAsUser\" function. This works fine as long as there is a

相关标签:
4条回答
  • 2021-01-01 04:05

    You cannot create a new session from a service. Sessions are managed by the OS. New ones get created when users logon interactively.

    0 讨论(0)
  • 2021-01-01 04:09

    What about the LogonUser function?

    http://winapi.freetechsecrets.com/win32/WIN32LogonUser.htm

    0 讨论(0)
  • 2021-01-01 04:13

    @Robert, I know this is an old question and that you've already found something that works for you but in my case I was looking for something similar to your original question and I did finally figure it out so I thought I'd share. My solution uses only .NET and a COM reference not the Win32 API mentioned in your title, but I'm guessing that wasn't really a requirement for you.

    I've written a simple utility to using the Remote Desktop ActiveX control (COM Reference). If you paste this code into a Class Library you can then call it by simply passing in the server, username, domain, and password and everything is done for you without any other interaction required. Once the method is complete you can then call your "CreateProcessAsUser" Code. I've written this utility in a way so that you could call it every time but initiating an RDP session takes several seconds so for performance sake I'd suggest you write another method to enumerate the sessions and see if your user is logged in and only call this utility when you determine that your user isn't logged in (That's what I did in my actual project). If you feel you need help with that post in the comments and I'll share how I did that but It's not really part of this question so for now I'm leaving it out.

    Here's a link back to my question that has a few more requirements/details than this question.

    Create Windows Session programmatically from Console or Windows Service

    And here's my RDP utility. After you put this code in a class library you can then call it from a console app, winForms app, or from a windows service running on the same machine or from a remote machine.

    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using AxMSTSCLib;
    
    namespace Utility.RemoteDesktop
    {
        public class Client
        {
            private int LogonErrorCode { get; set; }
    
            public void CreateRdpConnection(string server, string user, string domain, string password)
            {
                void ProcessTaskThread()
                {
                    var form = new Form();
                    form.Load += (sender, args) =>
                    {
                        var rdpConnection = new AxMSTSCLib.AxMsRdpClient9NotSafeForScripting();
                        form.Controls.Add(rdpConnection);
                        rdpConnection.Server = server;
                        rdpConnection.Domain = domain;
                        rdpConnection.UserName = user;
                        rdpConnection.AdvancedSettings9.ClearTextPassword = password;
                        rdpConnection.AdvancedSettings9.EnableCredSspSupport = true;
                        if (true)
                        {
                            rdpConnection.OnDisconnected += RdpConnectionOnOnDisconnected;
                            rdpConnection.OnLoginComplete += RdpConnectionOnOnLoginComplete;
                            rdpConnection.OnLogonError += RdpConnectionOnOnLogonError;
                        }
                        rdpConnection.Connect();
                        rdpConnection.Enabled = false;
                        rdpConnection.Dock = DockStyle.Fill;
                        Application.Run(form);
                    };
                    form.Show();
                }
    
                var rdpClientThread = new Thread(ProcessTaskThread) { IsBackground = true };
                rdpClientThread.SetApartmentState(ApartmentState.STA);
                rdpClientThread.Start();
                while (rdpClientThread.IsAlive)
                {
                    Task.Delay(500).GetAwaiter().GetResult();
                }
            }
    
            private void RdpConnectionOnOnLogonError(object sender, IMsTscAxEvents_OnLogonErrorEvent e)
            {
                LogonErrorCode = e.lError;
            }
            private void RdpConnectionOnOnLoginComplete(object sender, EventArgs e)
            {
                if (LogonErrorCode == -2)
                {
                    Debug.WriteLine($"    ## New Session Detected ##");
                    Task.Delay(10000).GetAwaiter().GetResult();
                }
                var rdpSession = (AxMsRdpClient9NotSafeForScripting)sender;
                rdpSession.Disconnect();
            }
            private void RdpConnectionOnOnDisconnected(object sender, IMsTscAxEvents_OnDisconnectedEvent e)
            {
                Environment.Exit(0);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-01 04:22

    This isn't quite the solution for the question I asked, but it was the solution that helped achieve what I was trying to achieve by asking this question, if you see what I mean.

    Rather than have having a windows services that creates a server session you can configure windows to automatically logon at boot time. This still means someone could accenditally log off, but cures the main reason for sessions disappearing: the server being rebooted. Use the following steps to activate auto-logon:

    1. Press the Windows key + R on your keyboard to launch the “Run” dialog box.
    2. Type regedit and hit enter to open the Registry Editor
    3. Then browse to HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\WindowsNT\CurrentVersion\Winlogon\
    4. Set AutoAdminLogon = 1 (create it if doesn't exist its a string variable)
    5. Set DefaultUserName = your username (create it if doesn't exist its a string variable)
    6. Set DefaultPassword = your password (create it if doesn't exist its a string variable)

    Instructions were taken from this post: http://channel9.msdn.com/Blogs/coolstuff/Tip-Auto-Login-Your-Windows-7-User-Account

    0 讨论(0)
提交回复
热议问题