How to run a program automatically as admin on Windows 7 at startup?
I created my own parental control app to monitor my kids activity. The app's only GUI is a task bar icon. The program is installed as admin. I'd like this program to be started up automatically as admin user on Windows startup, so that standard users cannot kill it from task ma开发者_如何学Gonager.
I can create a registry key at:
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
to make it run automatically when Windows starts up. The problem is that the program is started as the logged in (standard) user.
How can I make it run in an elevated mode? Is this possible at all in Win7?
You need to plug it into the task scheduler, such that it is launched after login of a user, using a user account that has administrative access on the system, with the highest privileges that are afforded to processes launched by that account.
This is the implementation that is used to autostart processes with administrative privileges when logging in as an ordinary user.
I've used it to launch the 'OpenVPN GUI' helper process which needs elevated privileges to work correctly, and thus would not launch properly from the registry key.
From the command line, you can create the task from an XML description of what you want to accomplish; so for example we have this, exported from my system, which would start notepad with the highest privileges when i log in:
<?xml version="1.0" encoding="UTF-16"?>
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<Date>2015-01-27T18:30:34</Date>
<Author>Pete</Author>
</RegistrationInfo>
<Triggers>
<LogonTrigger>
<StartBoundary>2015-01-27T18:30:00</StartBoundary>
<Enabled>true</Enabled>
</LogonTrigger>
</Triggers>
<Principals>
<Principal id="Author">
<UserId>CHUMBAWUMBA\Pete</UserId>
<LogonType>InteractiveToken</LogonType>
<RunLevel>HighestAvailable</RunLevel>
</Principal>
</Principals>
<Settings>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
<AllowHardTerminate>true</AllowHardTerminate>
<StartWhenAvailable>false</StartWhenAvailable>
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
<AllowStartOnDemand>true</AllowStartOnDemand>
<Enabled>true</Enabled>
<Hidden>false</Hidden>
<RunOnlyIfIdle>false</RunOnlyIfIdle>
<WakeToRun>false</WakeToRun>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<Priority>7</Priority>
</Settings>
<Actions Context="Author">
<Exec>
<Command>"c:\windows\system32\notepad.exe"</Command>
</Exec>
</Actions>
</Task>
and it's registered by an administrator command prompt using:
schtasks /create /tn "start notepad on login" /xml startnotepad.xml
this answer should really be moved over to one of the other stackexchange sites, as it's not actually a programming question per se.
schtasks /create /sc onlogon /tn MyProgram /rl highest /tr "exeFullPath"
This is not possible.
However, you can create a service that runs under an administrative user.
The service can run automatically at startup and communicate with your existing application.
When the application needs to do something as an administrator, it can ask the service to do it for it.
Remember that multiple users can be logged on at once.
I think that using the task scheduler to autostart programs is not very user friendly, and sometimes it has had side effects for me (e.g. tray icon for a program is not added).
To remedy this, I have made a program called Elevated Startup that first relaunches itself with administrator privileges, then it launches all files in a directory. Since Elevated Startup is now elevated, all the programs it then launches is also given administrator privileges. The directory is on the start menu next to the classic Startup directory, and works very much the same.
You may encounter one UAC dialog when the program relaunches itself, depending on your UAC settings.
You can get the program here: https://stefansundin.github.io/elevatedstartup/
Setting compatibility of your application to administrator (Run theprogram as an administrator)
.
Plug it into task scheduler
, then turn off UAC
.
You can do this by installing the task while running as administrator via the TaskSchedler library. I'm making the assumption here that .NET/C# is a suitable platform/language given your related questions.
This library gives you granular access to the Task Scheduler API, so you can adjust settings that you cannot otherwise set via the command line by calling schtasks
, such as the priority of the startup. Being a parental control application, you'll want it to have a startup priority of 0 (maximum), which schtasks
will create by default a priority of 7.
Below is a code example of installing a properly configured startup task to run the desired application as administrator indefinitely at logon. This code will install a task for the very process that it's running from.
/*
Copyright © 2017 Jesse Nicholson
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
/// <summary>
/// Used for synchronization when creating run at startup task.
/// </summary>
private ReaderWriterLockSlim m_runAtStartupLock = new ReaderWriterLockSlim();
public void EnsureStarupTaskExists()
{
try
{
m_runAtStartupLock.EnterWriteLock();
using(var ts = new Microsoft.Win32.TaskScheduler.TaskService())
{
// Start off by deleting existing tasks always. Ensure we have a clean/current install of the task.
ts.RootFolder.DeleteTask(Process.GetCurrentProcess().ProcessName, false);
// Create a new task definition and assign properties
using(var td = ts.NewTask())
{
td.Principal.RunLevel = Microsoft.Win32.TaskScheduler.TaskRunLevel.Highest;
// This is not normally necessary. RealTime is the highest priority that
// there is.
td.Settings.Priority = ProcessPriorityClass.RealTime;
td.Settings.DisallowStartIfOnBatteries = false;
td.Settings.StopIfGoingOnBatteries = false;
td.Settings.WakeToRun = false;
td.Settings.AllowDemandStart = false;
td.Settings.IdleSettings.RestartOnIdle = false;
td.Settings.IdleSettings.StopOnIdleEnd = false;
td.Settings.RestartCount = 0;
td.Settings.AllowHardTerminate = false;
td.Settings.Hidden = true;
td.Settings.Volatile = false;
td.Settings.Enabled = true;
td.Settings.Compatibility = Microsoft.Win32.TaskScheduler.TaskCompatibility.V2;
td.Settings.ExecutionTimeLimit = TimeSpan.Zero;
td.RegistrationInfo.Description = "Runs the content filter at startup.";
// Create a trigger that will fire the task at this time every other day
var logonTrigger = new Microsoft.Win32.TaskScheduler.LogonTrigger();
logonTrigger.Enabled = true;
logonTrigger.Repetition.StopAtDurationEnd = false;
logonTrigger.ExecutionTimeLimit = TimeSpan.Zero;
td.Triggers.Add(logonTrigger);
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new Microsoft.Win32.TaskScheduler.ExecAction(Process.GetCurrentProcess().MainModule.FileName, "/StartMinimized", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(Process.GetCurrentProcess().ProcessName, td);
}
}
}
finally
{
m_runAtStartupLock.ExitWriteLock();
}
}
A program I wrote, farmComm, may solve this. I released it as open-source and Public Domain.
If it doesn't meet your criteria, you may be able to easily alter it to do so.
farmComm:
- Runs at boot-up under a service, which continues when users log in or out.
- In Session 0
- Under the user "NT AUTHORITY\SYSTEM."
- Spawns arbitrary processes (you choose);
- Also in Session 0
- "Invisibly," or without showing any user interface/GUI
- With access to graphics hardware (e.g. GPUs).
- Responds to the active session, even if it changes, including the Secure Desktop. This is how it:
- Only spawns processes after a user is idle for 8.5 minutes
- Terminates spawns when a user resumes from idle
The source scripts are available here:
https://github.com/r-alex-hall/farmComm
You should also consider the security implications of running a process as an administrator level user or as Service. If any input is not being validated properly, such as if it is listening on a network interface. If the parser for this input doesn't validate properly, it can be abused, and possibly lead to an exploit that could run code as the elevated user. in abatishchev's example it shouldn't be much of a problem, but if it were to be deployed in an enterprise environment, do a security assessment prior to wide scale deployment.
I think the task scheduler would be overkill (imho). There is a startup folder for win7.
C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Just create a shortcut for your autostart Applicaton, edit the properties of the shortcut and have it always run as administrator.
Your kids could close it of course, but if they are tech-savvy they always find a way to keep you out. I know i did when i was younger.
Good luck!
精彩评论