If there was a command-line utility that could compete with robocopy in terms of usefulness, it’s PsExec. The Sysinternals PsExec utility is as ubiquitous as they come in an IT admin arsenal. This tool allows administrators to remotely run commands just as if they were on the local computer.
To cover the PsExec tool in depth, it was fitting to cover this coveted tool in an ATA Ultimate Guide. In this guide, you will learn what psexec is, what it’s capable of any many examples of how to use this useful tool.
What is PsExec.exe?
If you’re new to IT or perhaps haven’t had the need to run commands and tools on remote computers, you might not know what psexec is.
PsExec or psexec.exe is a command-line utility built for Windows. It allows administrators to run programs on local and more commonly remote computers. It is a free utility part of the Sysinternals pstools suite built by Mark Russinovich many years ago.
It was built to replace tools like telnet that forced you to open up ports and introduce security vulnerabilities. Nowadays, we have other options like PowerShell Remoting and the Invoke-Command
PowerShell cmdlet but PsExec still has its place.
PsExec allows full interactivity for console application without having to install any software. As you’ll see through this Ultimate Guide, PsExec can launch interactive command prompts, run as local system on remote computers, run commands on multiple computers at once and more.
It supports all versions of Windows since Windows XP. That means, that yes, PsExec on Windows 10 is a thing too. It’s a simple tool to run that works on nearly everything but don’t confuse its simplicity with its capabilities!
Prerequisites
You simply need to be running a modern Windows operating system for PsExec to run on your local computer. However, you’re going to want to run psexec against remote computers. To do that, you’ll need to ensure a few items are in place.
If you don’t have these items in place now or unsure, don’t worry. In the next section, we’ll cover how to write some PowerShell to test your remote computers.
- A modern Windows computer (local)
- File and Printer Sharing open (remote computer, TCP port 445)
- The admin$ administrative share available (remote computer)
- You know a local account’s credential (remote computer)
As of this writing, PsExec is at v2.2 and will be the version you’ll be learning about in this article.
Installing PSexec (With Remote Computer Setup)
Technically, you don’t install PsExec since it’s just a command-line utility but close enough. Since no installation is necessary, you simply need to download and extract it from the PsTools zip file. PsExec isn’t available as a standalone utility and is part of the PsTools suite of tools.
Downloading PSExec
You can either extract the ZIP file manually or here’s a handy PowerShell snippet to download and extract PsExec from its pstools ZIP file. Note that this removes all of the other PsTools tools. Many are still handy but we’re not going to cover those in this article.
PS> Invoke-WebRequest -Uri 'https://download.sysinternals.com/files/PSTools.zip' -OutFile 'pstools.zip'
PS> Expand-Archive -Path 'pstools.zip' -DestinationPath "$env:TEMP\pstools"
PS> Move-Item -Path "$env:TEMP\pstools\psexec.exe" .
PS> Remove-Item -Path "$env:TEMP\pstools" -Recurse
Remote Computer Configuration
Once you have PsExec downloaded, you’ll then need to ensure any remote computer you’re going to run it on is open. PsExec has simple requirements; File and Printer Sharing enabled and the admin$ administrative share available.
You could go to all of the remote computers, open up the Windows Firewall applet, go to Allowed Apps and enable File and Printer Sharing on all computers as you see below.
Note that File and Printer Sharing is a known security risk so ensure only the Private firewall profile is enabled.
Or you could visit each computer and run the netsh utility to open it up via:
> netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=Yes
Or you could use PowerShell’s Set-NetFirewallRule
cmdlet to do it.
PS51> Set-NetFirewallRule -DisplayGroup "File And Printer Sharing" -Enabled True -Profile Private
If you’d rather not visit each computer, you have PowerShell Remoting available and you’re in an Active Directory domain, you could also open up the firewall on many computers at once using the Invoke-Command
cmdlet.
PS51> Invoke-Command -ComputerName PC1, PC2, PC3 -ScriptBlock { Set-NetFirewallRule -DisplayGroup "File And Printer Sharing" -Enabled True -Profile Private }
Using PsExec
Before you can run, you need to walk. If you’ve never used PsExec before, you’re in for a treat! Be sure to read this section first to get your feet wet to learn the basics before jumping in the deep end later in this article.
The first time you run PsExec on a new system, you will immediately see the PsExec license agreement come up. You’ll have to click on the Agree button to begin using it.
If you’d like to prevent the license agreement from being displayed, you can silently accept it using the /accepteula
switch as shown below.
You’ll learn a few tricks at silencing this EULA popup on local and remote computers later in the article.
Finding Help
When exploring PsExec, you shouldn’t use any switch at all. When you simply run psexec with no switches, it will return all options and a brief explanation of what each does. All of the options are in the below table for your convenience.
Switch | Explanation |
---|---|
-a | Separate processors on which the application can run with commas where 1 is the lowest numbered CPU. For example, to run the application on CPU 2 and CPU 4, enter: “-a 2,4” |
-c | Copy the specified program to the remote system for execution. If you omit this option the application must be in the system path on the remote system. |
-d | Don’t wait for process to terminate (non-interactive). |
-e | Does not load the specified account’s profile. |
-f | Copy the specified program even if the file already exists on the remote system. |
-i | Run the program so that it interacts with the desktop of the specified session on the remote system. If no session is specified the process runs in the console session. Some have reported best results always using the -s switch with -i due to windows being unintelligible. |
-h | If the target system is Vista or higher, has the proc |
-l | Run process as limited user (strips the Administrators group and allows only privileges assigned to the Users group). On Windows Vista the process runs with Low Integrity. |
-n | Specifies timeout in seconds connecting to remote computers. |
-p | Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password. |
-r | Specifies the name of the remote service to create or interact. with. |
-s | Run the remote process in the System account. |
-u | Specifies optional user name for login to computer. |
-v | Copy the specified file only if it has a higher version number or is newer on than the one on the remote system. |
-w | Set the working directory of the process (relative |
-x | Display the UI on the Winlogon secure desktop (local system only). |
-arm | Specifies the remote computer is of ARM architecture. |
-priority | Specifies -low, -belownormal, -abovenormal, -high or |
-realtime | run the process at a different priority. Use |
-background | run at low memory and I/O priority on Vista. |
computer | Direct PsExec to run the application on the computer or computers specified. If you omit the computer name PsExec runs the application on the local system, and if you specify a wildcard (\*), PsExec runs |
@file | PsExec will execute the command on each of the computers listed in the file. |
-accepteula | This flag suppresses the display of the license dialog. |
-nobanner | Do not display the startup banner and copyright message. |
Running a Simple Remote Command
At its most basic, PsExec requires two parameters: a computer name and a command to run. If you have a command to run on the remote computer that doesn’t require any arguments like hostname
, you can simply add it after the computer name.
Note that if you don’t specify a full file path, the command to run must be in the user or system path. Also, if you have a program with spaces in the name, you can always enclose the program in spaces such as “my application.exe”.
> psexec \\REMOTECOMPUTER hostname
You can see below that to execute the hostname
command on the CONTOSODC1 computer, you define it’s UNC path followed by the command. PSExec will then connect to the remote computer securely, execute the command and return the output. In this case, the hostname
command returned the hostname of the computer which is CONTOSODC1.
If the command isn’t cmd
or another console, PsExec will quickly exit the remote session and return the exit code the remote process returned.
Note: The error or exit code returned from psexec is not coming from PsExec itself. Instead, it’s coming from the command that psexec executed on the remote computer.
How PsExec Works on Remote Computers
PsExec goes through a few steps to execute programs on remote computers.
- Create a PSEXESVC.exe file in C:\Windows.
- Create and start a Windows service on the remote computer called PsExec.
- Execute the program under a parent process of psexesvc.exe.
- When complete, the PsExec Windows service will be stopped and removed.
When the process doesn’t work 100% correctly you may have to manually remove the service using the sc command.
Running a Simple Local Command
Even though PsExec is best known for running commands on remote computers, you can also run commands locally.
You can run commands locally by simply not providing a computer name like below.
> psexec <local command or EXE file>
Why would you do this? One reason would be to execute commands as the local SYSTEM account. You can use the -s
switch to run any command as SYSTEM locally or remotely as you’ll learn more about later.
Take a look at the short video below. Notice that you simply need to provide the -s
switch along with the command interpreter executable for psexec to launch a new command session as NT AUTHORITY\SYSTEM.
PsExec Commands (Getting More Advanced)
Once you’ve got the basics down, you can then start learning more advanced techniques in psexec. PsExec can do a lot more than just run a single command on a single computer.
Running commands on multiple computers
PsExec isn’t just limited to running commands on one remote computer at a time. This tool also has support to copy programs and run commands on multiple computers at once.
You can run PsExec on multiple computers at once a few different ways.
Comma-separated Computer Names
Typically when running a command on a single remote computer, you will specify a single computer name like \\REMOTECOMPUTER
. You can also specify multiple computers separated by commas like below.
> psexec \\REMOTECOMPUTER1,REMOTECOMPUTER2,REMOTECOMPUTER3
All Computers in an Active Directory Domain
If you’re running PsExec on an Active Directory domain-joined computer and you’d like to blast out a command execution on all computers in that domain, use a wildcard.
PsExec will search your entire Active Directory domain and attempt to run a command on every computer. Below is example syntax on how PsExec will attempt to connect to every computer on the domain the executing computer is a part of and run the hostname
command.
> psexec \\* hostname
PsExec v2.2 - Execute processes remotely
Copyright (C) 2001-2016 Mark Russinovich
Sysinternals - www.sysinternals.com
Enumerating domain...
Note that if you use an asterisk to find all computers in a domain while the local computer is part of a workgroup, you will receive the error
A system error has occurred: 6118
.
Using a wildcard forces PsExec to essentially run the command net view /all
to first find all computers in the domain. This is an outdated way to find computer information due to its dependency on NetBIOS.
Reading from a File
Another way you can run commands on multiple computers at once is to use a text file. Using the syntax @<filename.txt>
, PsExec will read every line in the text file as if it were a computer name. It will then process each computer individually.
Below you can see an example of using PowerShell to create a text file of line-delimited computer names and using that as input for psexec.
Copying local programs to the remote computer
Using the -c
switch, psexec will copy any local program to the remote computer prior to execution.
Perhaps you have an EXE on your local computer in a C:\Tools folder and would like to run it on a remote computer. You can do so using the following syntax:
> psexec \\REMOTECOMPUTER -c C:\Tools\program.exe
When you use the -c
switch and don’t specify an executable file, PsExec will still copy the file but you’ll receive an error stating system cannot find the file specified. This happens because PsExec will always attempt to run the file you copy.
If you need to copy files to remote computers prior to using PsExec, use the Copy-Item
PowerShell cmdlet instead.
Running Remote Processes under Alternate Credentials
Another popular use case of PsExec is to run commands under alternative accounts. By default, PsExec will attempt to connect to the remote computer under your currently-logged-in account. More specifically, it will impersonate your account on the remote computer.
Using the -u
and optional -p
switch allows you to connect to the remote computer with an alternative user account. PsExec will then encrypt both the username and password and send them to the remote computer for authentication.
For example, if you’re in a workgroup, you’ll always need to specify the username to authenticate to the remote computer as.
> psexec \\REMOTECOMPUTER hostname -u localadmin -p secret-p@$$word
If both computers are a member of Active Directory, be sure to preface the user account with the domain name.
> psexec \\REMOTECOMPUTER hostname -u contoso.local\domainadmin -p secret-p@$$word
Note that when you do not use the -u
switch, psexec impersonates your logged-in account on the remote computer. It will not have access to any network resources.
Running Processes as the LOCAL SYSTEM Account
One of the most useful features of running PsExec under an alternative account is using the -s
switch. This switch allows PsExec (and your remotely-executed application) to run under the remote (or local) computer’s LOCAL SYSTEM account.
Notice below I didn’t include a remote computer name. PsExec will just as gladly run on the local computer as well. In this instance, I’m using the -s
option to tell PsExec to launch a local command prompt as the LOCAL SYSTEM account.
To run a command prompt as LOCAL SYSTEM on a remote computer, add the computer name to the reference like below:
> psexec -s \\REMOTECOMPUTER cmd
Launching GUI Applications Remotely
Another useful PsExec switch is -i
. By default, PsExec does not allow the remotely-executed command to bring up any windows on the remote computer. This is helpful because if you’re executing commands remotely, you’re not going to see the screen anyway.
But perhaps you need to bring up programs for your users. You personally won’t be using the application but an end-user will. In that case, use the -i
switch.
Maybe you need to bring up a notepad window on a remote computer. Not a problem. Run notepad.exe with the -i
switch and PsExec will open up Notepad.
> psexec -i \\REMOTECOMPUTER notepad
Be sure to also use the -d
switch to disconnect when the interactive window is brought up though. By default, PsExec will wait for the process it executed to complete. If the remote process (Notepad in this case) is kept running, PsExec will never return control.
Using the -d
switch with -i
will tell PsExec to not wait for the remote process to finish. Instead, it will disconnect and return control to you as soon as the remote process is executed.
Redirecting Output
Psexec will rely any output sent from the remote process to your local session. Typically, this output will go directly to your local console. But if you’d like to redirect it, you can do so using typical redirection operators.
For example, if you’d like to run a command and silence all output, you could redirect output and errors to null using ^> nul ^2^&1
.
Note the special characters are escaped with a hat. (
^
).
PsExec Use Cases
Once you’ve learned how to use psexec, you’ll inevitably come across various specific use cases. In this section, you’ll learn some real-world use cases and examples using psexec.
Launching a Remote Command Prompt (psexec cmd
)
One of the most common use cases is launching PsExec as an interactive command prompt. PsExec doesn’t just run commands remotely. It can also send command output back to your console. Because of this, it can make a great telnet (if anyone is still using that) or perhaps PowerShell Enter-PSSession
replacement.
To launch a remote command, specify the remote computer name and run the cmd application. Cmd is the Windows command interpreter. Since PsExec supports interactive use, it will gladly return a flashing cursor and a prompt.
At this point, the world is your oyster. You can run commands on your local computer via this “nested” command prompt and they will be executed on the remote computer.
To exit from the command prompt, type exit
. PsExec will stop the cmd
process on the remote computer and return focus to the local computer.
Do NOT use Ctrl-C to close out of an interactive cmd session. Always use
exit
. If you use Ctrl-C, the psexec session will remain running on the remote computer.
Installing Software Remotely
You can use PsExec as a poor-man’s software deployment tool. Perhaps you have an MSI installer that you need to run on one or more remote computers called setup.msi. This installer needs to be copied to the remote computers and then executed with the msiexec.exe utility with a few switches.
Below is an example of how you could use PsExec to remotely deploy software. This example copies setup.msi to the remote computer then launches the MSI installer interactively on as the SYSTEM account.
> psexec.exe \\REMOTECOMPUTER –i –s "msiexec.exe /i setup.msi" -c setup.msi
Accepting the EULA without the /accepteula
switch
As mentioned earlier, the first time PsExec runs, you’ll have to accept a EULA. You could use the /accepteula
switch but you could also “stage” it in the registry.
When launched for the first time, PsExec creates a registry key at HKCU\Software\Sysinternals\PsExec. Instead of that registry key, it creates a registry value called EulaAccepted with a DWORD value of 1.
Using your favorite method to modify the registry on remote computers, you simply need to create this key/value on computers you’d like to run PsExec on. Once created, no need to run /accepteula
!
Marrying PowerShell and PsExec
Before PowerShell, all we had was PsExec. Now, we have options. PowerShell can replace PsExec in many situations but complement it in others.
Building Computer Names with PowerShell
Instead of using \\*
to find all computers in the domain, you can use PowerShell instead. By using PowerShell, you can not only pick certain computers but you don’t have to use the firewall-prone net view /all
behavior.
You can use PowerShell to create a string containing all computer names separated by a comma. You can then pass that string to PsExec which will merrily process each one like you typed each one manually.
You can see below an example of using the Get-AdComputer
cmdlet part of the ActiveDirectory PowerShell module.
PS51> psexec "\\$((Get-AdComputer -Filter *).Name -join ',')" hostname
Enabling PowerShell Remoting Remotely
If you have remote computers you’d rather use PowerShell Remoting with instead of PsExec, you can use PsExec to enable them.
By running Enable-PSRemoting
or the winrm.cmd batch file on remote computers, you can quickly turn on PowerShell Remoting across many computers at once.
Below you can see an example of calling the winrm.cmd batch file on a remote computer running as the SYSTEM account. Because the output from that command isn’t needed, it’s silenced with 2>&1> $null
.
$computerName = 'REMOTECOMPUTER'
psexec "\\$Computername" -s c:\windows\system32\winrm.cmd quickconfig -quiet 2&>&1> $null
PsExec Error Messages
It’s worth mentioning again upfront that most error codes you see returned from PsExec are from the remote process; not from PsExec. But it’s helpful to have an understanding of these error codes and what they might mean.
If you’d like a reference on all Windows error codes, I recommend checking out this exhaustive list of Windows error codes.
Below is a list of common error codes you may see returned by PsExec.
Error Code | Explanation |
---|---|
-2146232576 | Typically returned by Windows Update when an error occurs. |
0 | Command executed successfully |
1 | Incorrect function. A problem happened. That’s about it. |
1603 | Fatal error during installation. This typically is returned by msiexec. |
2 | The system cannot find the file specified |
4 | The system cannot open the file. |
5 | Access is denied. |
6 | The handle is invalid. |
6118 | The list of servers for this workgroup is not currently available |
Your Feedback
ATA Ultimate Guides are big. There’s a lot of information in these and I’m bound to miss a thing here or there or make a mistake. If you notice anything wrong or think something should be added to this guide, please let me know via the comments. I’d be happy to credit you in the post.
Credits
- Thanks to Mathias (comments) for numerous feedback.
This article will show you how to install a program or application on a remote computer in your network without user interaction.
There are many ways to perform a remote installation;
in this article, I will show you how to install software on a remote computer with the PSexec tool
PSExec is a free Microsoft tool that allows you to execute programs and commands on other systems, complete with full interactivity for console applications, without manually installing client software.
- The Prerequisites:
- Step 1: Download The PSExec Tool
- Step 2: Download The MSI Package
- Step 3: Configure The Remote Computer Firewall
- Step 4: Run The Script
- Mistakes to avoid when remotely installing Software on Windows
The Prerequisites:
Here are the prerequisites you have to consider to perform a successful remote installation;
- Download the PSexec tool;
- Download the MSI package of the application you want to install;
- Ensure that the Windows 10 firewall on the remote computer does not block “File and Printer sharing” traffic;
- You need to have the administrator account password on the target PC, if not in the same domain;
Step 1: Download The PSExec Tool
Download PSExec tool from the Microsoft webpage, then extract the executable into a folder (Ex: C:\SysinternalsSuite\)
Step 2: Download The MSI Package
Download the MSI package of the application you want to install.
Important: Not all applications support silent mode when running the Setup.exe installer, and hence you need to download the MSI package instead.
Let’s say you want to install the Google Chrome browser.
You need to download the MSI package from the Chrome download page;
Step 3: Configure The Remote Computer Firewall
Ensure the Firewall on the remote computer allows “File and Printer sharing (SMB-In)” traffic on port TCP 445.
You can test if port TCP 445 is open using the PowerShell command “test-netconnection“
Step 4: Run The Script
- Open a command prompt as an administrator;
- Copy the MSI package on the remote computer using this command:
Copy c:\users\username\downloads\GoogleChromeStandaloneEnterprise64.msi \\ENDUSER-PC\C$
Where “ENDUSER-PC” is the name of the remote computer.
Note that you can also use the IP address of the remote computer instead of the computer name.
- In the command prompt, change the current directory to “C:\SysInternals”;
- Run the following command to start installing Google Chrome on the remote computer;
PsExec.exe \\ENDUSER-PC\ -i -s msiexec.exe /i "c:\GoogleChromeStandaloneEnterprise64.msi" /qn /norestart
PSExec will launch the GoogleChromeStandaloneEnterprise64.msi installer on the remote computer, which will install Google Chrome in quiet mode (/qn) without user interaction.
Mistakes to avoid when remotely installing Software on Windows
- Not checking system requirements: Before installing any software, it’s essential to check the system requirements to ensure that the Software is compatible with the target PC’s operating system and hardware.
- Not testing the installation process: Before installing Software remotely, it’s a good idea to test the installation process on a test machine to ensure that everything works as expected. This will help you identify and fix any issues before deploying the Software to production machines.
- Not having proper permissions: To install Software remotely, the user must have appropriate permissions to access the target PC. The installation process may fail if the user does not have the necessary permissions.
- Not checking for conflicts: Installing new Software on a computer with conflicting Software can cause unexpected problems. Before you install any software remotely, ensure there are no conflicts with existing Software.
- Not communicating with end-users: When you remotely install Software on a user’s computer, it’s important to communicate with the user to let them know what to expect. This can include letting them know when the installation will take place and what steps they need to take, if any.
- Not having a backup plan: Even with careful planning and testing, things can go wrong during the remote installation. It’s essential to have a backup plan in place in case something goes wrong. This can include having a plan to roll back the installation or having a backup image of the computer.
I hope you found this blog helpful. Before you go, I’d like to ask if you’d consider supporting my work. Running this blog requires a lot of time and dedication, and with more people using ad blockers and AI tools, ad revenue has been declining. Your support would allow me to keep creating the content you enjoy. Thank you for considering it..
Related
Skip to content
Background:
PSEXEC is nice little command line utility that I’ve had to use for many years now in managing and troubleshooting Windows PCs remotely. Psexec is part of the PSTOOLS collection by the famed Mark Russinovich. The latest version of Psexec can be downloaded at https://technet.microsoft.com/en-us/sysinternals/pstools.aspx
With Windows 7 and below, as long as you have domain admin rights you are able to run psexec without much drama. Unfortunately, with Windows 10 it isn’t as simple as before as there are plenty of reports of Windows 10 denying your Psexec connections. An example problem widely reported is below.
Solution:
To fix this you will need to allow 2 ports – TCP/445 and UDP/137. However, you will want to ensure only the IP addresses of admin PCs or servers are allowed for security reasons.
You will notice that if the remote Windows 10 firewall is disabled, the connection is allowed immediately. With this fix, the connection can take from 10-15 secs but will be allowed eventually.
Steps:
- Connect to the affected Windows 10 PC using your favourite remote access tool (eg VNC, RDP, etc).
- Open an ‘elevated’ CMD prompt and enter the commands below (you can copy and paste this 2 lines in one go).
netsh advfirewall firewall add rule name="Allow PSEXEC TCP-445" dir=in action=allow protocol=TCP localport=445 remoteip=(your admin/server IPs here separated by comma and no spaces) netsh advfirewall firewall add rule name="Allow PSEXEC UDP-137" dir=in action=allow protocol=UDP localport=137 remoteip=(your admin/server IPs here separated by comma and no spaces)
3. Now try to run psexec on your PC using the command below
psexec \\<pc name> cmd
Finally, you are in!
4. Type exit to close PSEXEC session and return to CMD prompt.
В Windows для выполнения некоторых действий недостаточно иметь права администратора. Например, вы не сможете заменить или удалить системные файлы, некоторые ветки реестра, остановить системные службы или выполнить другие потенциально небезопасные действия, которые могут нарушить стабильность системы. Системному администратору в таких случая приходится назначать себе владельцем таких объектов или выполнять действия от имени системы. В этой статье мы рассмотрим, как запустить программу или командную строку в Windows от имени привилегированного аккаунта SYSTEM (Local System).
Содержание:
- Запуск командной строки от Local System в старых версиях Windows (до Vista)
- Запуск программ от имени системы с помощью PSExec в Windows 10
Встроенная учетная запись SYSTEM используется диспетчером управления службами SCM (Service Control Manager) для запуска и управления системными службами. Из-под учетной записи System (может называться NT AUTHORITY\SYSTEM, Local System или Computer\LocalSystem)запускается большинство системных служб и процессов (в том числе ядро NT Kernel). Откройте оснастку управления службами services.msc и обратите внимание на службы, у который в столбце LogOnAs указано Local System. Эти службы запушены из-под учетной записи SYSTEM.
Запуск командной строки от Local System в старых версиях Windows (до Vista)
В снятых с поддержки Windows XP и Windows Server 2003 была интересная возможность, позволяющая запустить программу или же интерактивную командную строку (cmd) с правами системы через планировщик. Достаточно войти с правами администратора, открыть командную строку и набрать в ней:
at 12:23 /interactive cmd.exe
, где
12:23
– текущее время + одна минута (в 24 часовом формате).
После наступления указанного времени перед вами открывается окно командной строки, запущенное с правами Local System. Если вы выполнили эту команду в терминальном (rdp) сессии Windows Server 2003/XP, имейте в виду, что командная строка с правами System отображается только в консольной сессии (как подключиться к rdp консоли).
В Windows 10 запуск интерактивной строки с помощью команды at не поддерживается. Вместо него рекомендуется использовать
schtasks.exe
.
Команда AT признана нерекомендуемой. Используйте вместо нее schtasks.exe. Внимание! В соответствии с повышенной безопасностью данное задание будет выполняться в запланированное время, но не интерактивно. Если требуется интерактивное задание, воспользуйтесь служебной программой schtasks.exe (для получения дополнительных сведений введите schtasks /?). Такой запрос не поддерживается.
Запуск программ от имени системы с помощью PSExec в Windows 10
Начиная с Windows 7 трюк с запуском интерактивной командной строки от имени системы через планировщик не работает. Для запуска команд от имени NT Authority\ System можно использовать утилиту PSExec.exe от Sysinternals.
Утилиту
PSExec.exe
можно скачать на сайте Microsoft https://docs.microsoft.com/en-us/sysinternals/downloads/psexec. Утилита PSExec знакома любому администратору и в первую очередь предназначена для удаленного управления Windows, однако в ней есть полезная возможность запуска процессов от имени System. Некоторые антивирусы могут опознавать PSExec.exe как потенциально небезопасную программу (с помощью psexec кстати распространялся печально известный вирус notpetya),
Утилита PSExec не требует установки. Откройте командную строку с правами администратора (“Run as administrator”) перейдите в каталог, в котором находится исполняемый файл PSexec.exe и наберите:
psexec -i -s cmd.exe
параметр -i запускает приложение в интерактивном режиме (пользователь может взаимодействовать с программой на рабочем столе, если это параметр не указывать, процесс запускается в консольной сесии), —s означает что командную строку нужно запустить из-под системы
При первом запуске PsExec попросит вас принять лицензионное соглашение.
После выполнения команды появится новое окно с командной строкой, запущенной из-под учетной записи NT Authority\System. Проверьте это, выполнив команду:
whoami
Таким образом вы запустить любую программу, команду или скрипт с правами системы. Достаточно в параметре утилиты PsExec изменить cmd.exe на имя исполняемого файла нужной программы.
В открывшемся окне командной строки вы можете выполнять любые команды в контексте SYSTEM. Теперь вы сможете изменить, переименовать или удалить системные файлы/ветки реестра, владельцем которых является TrustedInstaller или SYSTEM. Все программы или процессы, которые вы запустите их этого окна также будут запущены с повышенными привилегиями LocalSystem. Например, можно остановить системную службу, или закрыть дескриптор занятого системой файла.
С помощью PSExec вы можете получить интерактивную командную с правами NT AUTORITY\СИСТЕМА с удаленного компьютера. Для этого используется команда:
psexec -s \\msk-PCBuh2 cmd.exe
При появлении ошибки
couldn’t install PSEXESVC service
, убедитесь, что:
- командная строка запущена от имени администратора;
- проверьте, возможно служба PSEXESVC уже запущена.
Есть еще ряд сторонних утилит для запуска программ от имени System (AdvancedRun , RunAsSystem, PowerRun), но я не вижу смысла использовать их смысла. Т.к. во-первых это сторонние утилиты, и вы не можете гарантировать что в их коде нет вредоносных закладок, и во-вторых официальная утилита PsExec от Microsoft отлично справляется с задачей.
Вы тут: Главная → Windows → Как выполнять команды и скрипты от имени системы средствами Windows
В комментариях статьи про diskusage читатель спросил, может ли утилита показать размер папки C:\Windows\CSC
, где хранится кэш автономных файлов.
Очевидно, в его организации с проблемой сталкиваются регулярно, а для анализа приходится выключать ОС
Сегодня я покажу способ, позволяющий решать такие задачи, не прекращая работу Windows. В качестве примера я решу проблему читателя двумя способами — с помощью diskusage и PowerShell. Причем подход вполне актуален для diskusage, поскольку утилита на данный момент не видит содержимое папок, на которые у администратора нет прав.
Вы можете применять этот способ для любых задач! Объем файлов в папке — просто пример.
И да, все составляющие сегодняшнего рассказа – это компиляция ранее опубликованных в блоге решений.
[+] Сегодня в программе
Сторонние средства: psexec
В командной строке от имени администратора команда dir сообщает об отсутствии папки C:\Windows\CSC
. Однако PowerShell подтверждает наличие пути и сообщает, что для доступа недостаточно прав.
Вообще-то, в статье про diskusage я изначально ссылался на способ с psexec, позволяющий интерактивно запускать приложения от имени системы. Другими словами, с помощью утилиты можно было запустить командную строку или PowerShell от имени SYSTEM…
psexec64 -i -s cmd
…и узнать, что для доступа в папку нужны права SYSTEM
Дальше можно просто выполнять необходимые команды.
Системные средства: планировщик заданий
Допустим, что стороннее ПО, даже с подписью Microsoft из набора sysinternals, строго запрещено службой безопасности и/или блокируется политиками. Однако с правами администратора можно создавать и выполнять задания в планировщике для запуска команд и скриптов.
Например, я показывал в блоге автоматическое выполнение задач на восходе и закате солнца. Там ключевую роль играло запланированное задание, которое запускается от имени системы. Здесь тот же подход.
Шаг 1 — Создайте простое задание на разовый запуск программы
В качестве действия укажите:
- Команда:
powershell
- Параметры для выполнения команды:
-ExecutionPolicy Bypass -Noprofile -Command ваша_команда
или
Параметры для выполнения скрипта:-ExecutionPolicy Bypass -Noprofile -File путь_к_файлу.ps1
В нашем примере diskusage запускается с желаемыми ключами командной строки и записывает результат в файл. Пример параметров для планировщика.
-ExecutionPolicy Bypass -Noprofile -Command "diskusage /humanReadable C:\Windows\CSC | Out-File -FilePath C:\temp\out.txt"
За неимением утилиты используем PowerShell — считаем и складываем размер всех файлов во всех папках (конечно, я не рекомендую применять этот подход ко всему диску :).
-ExecutionPolicy Bypass -Noprofile -Command "[math]::Round(((Get-ChildItem -Path C:\Windows\CSC -Recurse | Measure-Object length -Sum).Sum)/1mb,1) | Out-File -FilePath C:\temp\out.txt"
Шаг 2 — Настройте задание на запуск от имени системы
На вкладке Общие нажмите Изменить и введите SYSTEM или СИСТЕМА в зависимости от локализации.
Автоматизацию создания таких запланированных задач я разбирал с помощью schtasks и PowerShell. Остается запустить задание и открыть созданный файл. Все просто!
В отличие от psexec, из планировщика не работает интерактивный запуск приложений. Например, редактор реестра запустится, но взаимодействовать вы с ним не сможете. Однако выполнение команд и скриптов с правами системы отлично работает.
Заключение
Я всегда ощущаю некоторую неловкость, когда пишу для блога или канала Telegram материал, не содержащий ничего нового [относительно моих предыдущих публикаций]. Но я понимаю, что не все читали старые записи, равно как из поисковиков приходит множество людей по конкретным запросам. Поэтому какая-то польза от этого должна быть.
В данном случае у меня была и дополнительная мотивация. Фактически, эта статья – затравка для следующей, в которой мы посмотрим на эту же тему под более интересным углом.