如何在启动时在 Windows 7 上以管理员身份自动运行程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5427673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run a program automatically as admin on Windows 7 at startup?
提问by newman
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 manager.
我创建了自己的家长控制应用程序来监控我孩子的活动。该应用程序唯一的 GUI 是任务栏图标。该程序以管理员身份安装。我希望这个程序在 Windows 启动时以管理员用户身份自动启动,这样标准用户就无法从任务管理器中杀死它。
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.
使其在 Windows 启动时自动运行。问题是程序以登录(标准)用户身份启动。
How can I make it run in an elevated mode? Is this possible at all in Win7?
我怎样才能让它在提升模式下运行?这在Win7中可能吗?
回答by Petesh
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.
我用它来启动“OpenVPN GUI”助手进程,该进程需要提升权限才能正常工作,因此无法从注册表项正确启动。
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 描述来创建任务;例如,我们有这个,从我的系统导出,当我登录时,它将以最高权限启动记事本:
<?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.
这个答案真的应该移到其他 stackexchange 站点之一,因为它本身实际上并不是一个编程问题。
回答by msPark
schtasks /create /sc onlogon /tn MyProgram /rl highest /tr "exeFullPath"
回答by SLaks
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.
请记住,可以同时登录多个用户。
回答by stefansundin
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.
为了解决这个问题,我制作了一个名为 Elevated Startup 的程序,它首先以管理员权限重新启动,然后启动目录中的所有文件。由于 Elevated Startup 现在被提升,它随后启动的所有程序也被授予管理员权限。该目录位于经典启动目录旁边的开始菜单上,其工作方式非常相似。
You may encounter one UAC dialog when the program relaunches itself, depending on your UAC settings.
当程序重新启动时,您可能会遇到一个 UAC 对话框,具体取决于您的 UAC 设置。
You can get the program here: https://stefansundin.github.io/elevatedstartup/
你可以在这里获取程序:https: //stefansundin.github.io/elevatedstartup/
回答by stefansundin
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.
您可以通过TaskSchedler 库以管理员身份运行时安装任务来完成此操作。鉴于您的相关问题,我在这里假设 .NET/C# 是合适的平台/语言。
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.
该库使您可以精细地访问 Task Scheduler API,因此您可以通过调用 来调整无法通过命令行设置的设置schtasks
,例如启动的优先级。作为家长控制应用程序,您会希望它的启动优先级为 0(最大值),这schtasks
将默认创建优先级为 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();
}
}
回答by Wawan
Setting compatibility of your application to administrator (Run theprogram as an administrator)
.
将您的应用程序的兼容性设置为管理员(Run theprogram as an administrator)
。
Plug it into task scheduler
, then turn off UAC
.
将其插入task scheduler
,然后关闭UAC
。
回答by Alex Hall
A program I wrote, farmComm, may solve this. I released it as open-source and Public Domain.
我写的一个程序 farmComm 可以解决这个问题。我将它作为开源和公共领域发布。
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
- 在服务下启动时运行,在用户登录或退出时继续。
- 在会话 0
- 在用户“NT AUTHORITY\SYSTEM”下。
- 产生任意进程(您选择);
- 同样在会话 0
- “隐形”,或不显示任何用户界面/GUI
- 可以访问图形硬件(例如 GPU)。
- 响应活动会话,即使它发生变化,包括安全桌面。它是这样的:
- 仅在用户空闲 8.5 分钟后生成进程
- 当用户从空闲状态恢复时终止生成
The source scripts are available here:
源脚本可在此处获得:
回答by Curtis
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.
您还应该考虑以管理员级别用户或服务身份运行进程的安全隐患。如果任何输入未正确验证,例如它是否正在侦听网络接口。如果此输入的解析器未正确验证,则可能会被滥用,并可能导致漏洞利用,以提升的用户身份运行代码。在 abatishchev 的示例中,这应该不是什么大问题,但如果要将其部署在企业环境中,请在大规模部署之前进行安全评估。
回答by zhengtonic
I think the task scheduler would be overkill (imho). There is a startup folder for win7.
我认为任务调度程序会矫枉过正(恕我直言)。win7有启动文件夹。
C:\Users\miliu\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
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!
祝你好运!