Execute console commands on remote computers over a network. WinRM - remote work with PowerShell Winrm command parameters

This article discusses how to perform console commands on remote computers on the network, some very useful examples are given for system administrators teams.

I use 2 tools for remote execution of console commands: PsExec and WinRM, each of them has its own advantages.

PsExec

One of the excellent solutions to the problem posed in the title is to use the PsExec program from the great Mark Russinovich.

The program works on a client-server principle: a client runs on the local machine, which sends commands to a server on a remote computer. A special feature of this program is that the server part is installed automatically immediately before executing the command, and then removed. Thus, to execute commands on remote machines, it is enough to have administrative rights to them.

If PsExec is run as an administrator who is part of the same domain as the remote computer, then you don’t even need to enter any credentials. Otherwise, you can specify them on the command line, or PsExec will prompt you for them. PsExec works on OSes from Windows 2000 to 64-bit Windows Server 2008 R2.

The following features are very useful in PsExec:

  • Executing a command on a group of computers. Example: The following command forces the latest group policies to be applied:
    psexec @group.txt gpupdate /force
  • Running commands as the system account. Example: the following command will cause remote system force check for updates:
    psexec \\computer -s wuauclt /detectnow
  • Copying an executing program to a remote computer before executing it. Example: The following command will update this computer's security group membership Active Directory(access token) without reboot:
    psexec \\computer -c -s klist.exe purge

It is difficult to overestimate the usefulness of this program if you use scripts and the capabilities of console commands built into Windows.

Windows Remote Management

Initially it was server technology For remote control hardware, which was introduced in Windows Server 2003 R2 as part of the Hardware Management feature, but Microsoft recently released Windows package Management Framework, which includes PowerShell 2.0 and WinRM 2.0 and is installed on client OSes as an update. Details can be found in article KB968929.

The beauty of WinRM is the ease of deployment in a domain environment via WSUS as an optional OS upgrade and the power it provides when used together with PowerShell.

Using WinRM occurs through 2 commands.

winrm.cmd serves to configure settings and diagnose the WinRM client and server.

In order for the WinRM server to begin accepting commands, the Windows Remote Management service must be started and its initial configuration must be performed. Use the command

winrm quickconfig on the local machine, or a trick with your ears
psexec -s \\servername winrm quickconfig over the network using PsExec as the system account.

You will be prompted to automatically start the WinRM service and allow remote connections, agree;)

To successfully connect to a WinRM server (meaning the server part that receives commands) that is not part of the same domain as your client computer, you need to add this target server to the “trusted list” on the client with the following command:

winrm set winrm/config/client @(TrustedHosts="servername") , where instead of servername you can specify an IP address, or * (asterisk).

For users Windows Vista and Windows 7, not running as the built-in administrator (this is usually the case), you need to run the following command

reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

By default, there is a limit of 5 simultaneous WinRM connections from the client, to increase this number run the command

winrm s winrm/config/winrs @(MaxShellsPerUser="X")

winrs.exe— a client for sending requests to the server part. Example: The following command will force a reboot of the remote system...

winrs -r:servername shutdown /r /t 0

In a domain environment, the credentials of the running user are used when sending commands. To send commands on behalf of another user, use the -u:user -p:pass switches. Example: The following command will clear the local DNS name cache on the remote system

winrs -r:servername -u:user -p:pass ipconfig /flushdns

Remote Windows Management Using WinRM

Actually WinRM(or Windows Remote Management) and translates as “remote control Windows". WinRM– remote control service for operating systems Windows. It has been included in operating systems since Vista And Server 2008, For Windows XP And Server 2003 it needs to be installed separately from here. WinRM– the server part of the remote control application, to which it is possible to connect remotely using a client Windows Remote Shell (WinRS).

WinRM service based Web Services for Management (WS-Management) and uses HTTP (port 80) or HTTPS (443) and SOAP requests to get the job done. Regardless of the protocol used, all traffic sent WinRM is encrypted (unless you specifically disable this option). The default authentication protocol is Kerberos.

IN Windows Server 2008 WinRM installed, but (for security reasons) not enabled by default. To check if it is running WinRM on our machine, type in the command line winrm enumerate winrm/config/listener

If there is no answer, then WinRM not running. In order to set up WinRM on automatic start and allow remote connection to the computer, type the command winrm quickconfig or winrm qc

To prevent WinRM from asking for confirmation, you can add the key to the call -quiet. Find out information about more fine tuning You can see the built-in help WinRM: winrm help config

Well, turn it off WinRM you can use this command:
winrm delete winrm/config/listener?IPAdress=*+Transport=HTTP

Also everyone necessary settings can be done using group policies. To do this you need:

  • Set up a service WinRM to automatic start
  • Allow connections to the appropriate ports (80 and 443) in the firewall Windows
  • Customize element group policy Computer Configuration\Administrative Templates\Windows Components\Windows Remote Management\Remote Service Windows management\Allow automatic installation listeners (Computer Configuration\Administrative Templates\Windows Components\Windows Remote Management\WinRM Service\Allow automatic configuration of listeners). Here you will need to specify the IP addresses from which connections are allowed.

Now let's move on to use. To connect to a remote computer we use the utility WinRS. WinRS- abbreviation for Windows Remote Shell(remote environment Windows). WITH WinRS we can make remote requests to computers running WinRM. However, keep in mind that your machine also needs to be running WinRM to work with WinRS.

Main way to use WinRS is to execute commands on a remote machine. The computer name is specified by the key -r followed by the command to be executed, for example winrsr: SRV2 ipconfig / all runs on a remote computer SRV2 team ipconfig/all

The default protocol for communications is http, but you can also use https: winrs -r:https://SRV2 ipconfig /all

You can also use WinRS open an interactive session on a remote computer: winrs -r:SRV2 cmd.exe

This function is similar to connecting via telnet, but use WinRS Definitely better from a security point of view.

To use WinRM, all computers must be members of the same domain. If this is not the case in your case, then you can try lowering the security level. To do this, on the computer we want to access, enter the following commands:

« true")

« »}

WinRM set winrm/config/client @(TrustedHosts= « ComputerName" }

where ComputerName is the remote computer from which the connection will be made.

On the computer from which we will connect, enter:

WinRM set winrm/config/service/auth @(Basic= « true")

WinRM set winrm/config/client @(TrustedHosts= « »}

WinRM set winrm/config/client @(TrustedHosts="ComputerName" }

where ComputerName is the computer that we will manage.

Then we establish a connection using the command:

winrs -r:"ComputerName" : –u: Domain\Username –p: Password cmd.exe

where Domain\Username is a user account with administrative rights on the remote computer.

There are times when you need to run a command locally on the server (for example, configure an iSCSI Initiator). To do this, connecting via Remote Desktop and launching cmd is inconvenient, using Telnet is unsafe, I don’t want to install an ssh daemon on the server...

Especially for such advanced cases, Microsoft, starting with Windows Server 2003 R2, has provided administrators with a new management tool - Windows Remote Management (WinRM), which allows you to remotely execute commands using standard means OS, while ensuring the proper level of security.

You don't even have to install additional programs and components - everything that is called included:


Setting up WinRM
As an example, I will look at the process of setting up WinRM on Windows Server 2008. This procedure is no different from setting up WinRM, for example, on Windows Vista or Hyper-V Server.

The easiest way to configure WinRM is to use the quick configuration mode by typing in CMD:
winrm quickconfig
and answering in the affirmative (" y") to the question about creating a new listener object that listens on TCP port 80 and uses the HTTP protocol for communication between the client and the server.


And that’s it, the server can be managed remotely using the command:
winrs -r: <ИМЯ_СЕРВЕРА> <КОМАНДА>
,Where <ИМЯ_СЕРВЕРА> - name or IP address of the server to which the connection is made;
<КОМАНДА> - remote command that needs to be executed.


If the client and server are not members of the same domain, you will need to additionally specify the username under which the command will be run and its password:
winrs -r: <ИМЯ_СЕРВЕРА> -u: <ИМЯ_ПОЛЬЗОВАТЕЛЯ> -p: <ПАРОЛЬ> <КОМАНДА>

And at the same time, as the message that appears advises, add the server to the list of trusted nodes, or use a more reliable protocol for communication (HTTPS).

To add a host to the list of trusted ones, run on the client from which you plan to connect:
winrm set winrm/config/client @(TrustedHosts=" <ИМЯ_УЗЛА1> [,<ИМЯ_УЗЛА2> ]"}


Once configured, you can get information about existing listeners using the command:
winrm enumerate winrm/config/listener


You can delete an existing listener as follows:
winrm delete winrm/config/listener?Address=*+Transport=HTTPS


Configuring WinRM using HTTPS
In some cases, you may need to create a reliable channel to send commands securely between the client and server. You can use HTTPS for this.

However, to create a listener with HTTPS support, you will need a digital certificate, which you can request from a trusted Certificate Authority, or use various utilities for creating self-signed (self-signed) certificates, for example, Makecert, included in the Windows SDK. You can download Makecert separately from here .

To create a self-signed certificate, run the following command:
makecert -a sha1 -r -pe -n "CN= <ИМЯ_СЕРВЕРА> " -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localmachine -sky exchange -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12 -m 12 <ФАЙЛ_СЕРТИФИКАТА>
, Where <ИМЯ_СЕРВЕРА> corresponds to the name that the client will use when connecting to the server;
<ФАЙЛ_СЕРТИФИКАТА> - path to the file where the certificate with the public key will be saved.


A certificate with the private key will be created and placed in the certificate store local computer. Add it to your trusted root certificates:
certutil -addstore root cert.cer


Now browse the certificate store, find the required certificate there and write down its Thumbprint (Cert Hash):
certutil -store my


Finally, you can start creating an HTTPS listener. Enter the command:
winrm create winrm/config/Listener?Address=*+Transport=HTTPS @(Hostname=" <ИМЯ_УЗЛА> ";CertificateThumbprint=" <ХЭШ_СЕРТИФИКАТА> ";Port=" <ПОРТ> "}
,Where <ИМЯ_УЗЛА> - name that is specified when accessing the server
<ХЭШ_СЕРТИФИКАТА>- Thumbprint that you learned in the previous step (without spaces).
<ПОРТ> - port to which the client will connect (TCP 443 by default).


If enabled on the server Windows firewall, don't forget to add the rule:
netsh advfirewall firewall add rule name="allow WinRM on 4443" protocol=TCP dir=in localport=4443 action=allow

If you use self-signed certificates, you will have to add it to the trusted root certificates on the client.

After completing all the steps, you will finally be able to execute commands remotely.

I once had problems with WinRM on two servers.

1.SETSPN
On one, the problem was that the SPN of the HTTP/<имя сервера>were registered for some "left" account user.

I found these posts with the command
setspn -F -Q */<имя сервера>

Then I deleted them with the commands
setspn -D http/<имя сервера>.<имя домена> <имя домена>\<левая учётная запись>
setspn -D http/<имя сервера> <имя домена>\<левая учётная запись>

Then enable-psremoting -force completed successfully.

2. LANGUAGE PACK
And on the second server there was a tricky problem supposedly with the firewall Unable to check the status of the firewall, I looked through a bunch of sites, and discovered the solution intuitively based on the answer regarding the installed Language Pack.

WinRm QuickConfig
WinRM service is already running on this machine.
WSManFault
Message
ProviderFault
WSManFault
Message = Unable to check the status of the firewall.

Error number: -2147024894 0x80070002
The system cannot find the file specified.

The answer stated that this error can be cured by removing the additional Language Pack.
But I did it differently. I have an English operating system with an additional Russian language pack. I just changed the interface language to Russian.
Control Panel, Regional and Language Options, Languages ​​and Keyboards changed the interface language from English to Russian.
I logoffed and logged in again. Opened PowerShell and repeated WinRm QuickConfig

PS C:\Windows\system32> winrm qc

The WinRM service is not configured to allow remote control of the computer.
The following changes need to be made:

Create a WinRM listener on HTTP://* to accept WS-Man requests on any of this computer's IP addresses.

Make changes? y

WinRM service has been updated for remote management.

Created a WinRM listener on HTTP://* to accept WS-Man requests on any of this computer's IP addresses.

It was successful, but still not sufficient.

An Access Denied error appeared when trying to execute commands remotely on this server from another computer.

New-PSSession: [<имя сервера>] Connecting to remote server<имя сервера>failed with the following error message: Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.

Then I repeated Enable-PsRemoting

PS C:\Windows\system32>Enable-PsRemoting

WinRM Quick Setup
Running the "Set-WSManQuickConfig" command to enable it on this computer remote control using the WinRM service.
Necessary actions.
1. Start or restart (if already running) the WinRM service.
2. Changing the WinRM service type to "autostart".
3. Create a listener to accept requests on any IP address.
4. Configure firewall exceptions for WS-Management service traffic (http protocol only).

Continue?

(default value is "Y"):a
The WinRM service is already configured to accept requests on the computer.
The WinRM service is already configured to allow remote control of the computer.

Confirmation
Are you sure you want to perform this action?
Performing the "Register Session Configuration" operation on the "Session Configuration" target object
"Microsoft.PowerShell32" not found. The command "Register-PSSessionConfiguration Microsoft.PowerShell32" will be executed
-processorarchitecture x86 -force" to create the "Microsoft.PowerShell32" session configuration. The WinRM service will
restarted."
[Y] Yes - Y [A] Yes for all - A [N] No - N [L] No for all - L [S] Suspend - S [?] Help
(default value is "Y"):a

After that, WinRM worked as it should on this server.

Windows Remote Management is a Windows remote management service. Under this general name are hidden two tools that allow the user. Unlike the previous two Windows tools( and ), which allowed you to see what was happening on a remote computer on your screen and manipulate the remote computer using a mouse and keyboard, these two tools are radically different from them. The tools included in the Windows Remote Management service allow you to control your computer with just commands. These commands are run either from the command line or from Windows Power Shell. The only response about control is the response from the shell about the execution of the command. You are largely blindly sending commands to a remote computer and receiving monosyllabic answers about whether it was completed or not. Minimum amenities. But for computer administration this is just the thing.

Activating Windows Remote Management

Hidden under Windows Remote Management are two commands that allow you to run commands on a remote computer. These commands, as already mentioned, belong to two different shells: Windows Command Prompt and Windows Power Shell. I think everyone is familiar with the command Windows string. Well, Power Shell is a tool that is designed to replace the outdated command line. At first glance, these instruments are very similar. But in reality Power Shell is higher command line, which has not undergone major changes for a very long time. It was in connection with this that a replacement was prepared for him.

To be able to remotely control your computer using Windows Remote Management, the target computer must be properly configured. To do this, on the target computer you need to run the command (in a Windows command prompt window):

winrm quickconfig

This command enables and configures delayed automatic start Windows services Remote Management (by the way, you can also use the Services tool for), and also configures the appropriate exceptions for, which are necessary for the proper functioning of these tools.

But executing this command is not enough. For remote connections to become possible, the computer from which remote control will be carried out must be trusted by the target computer. The matter becomes easier if both of these computers are in the same domain - in this case, both computers are mutually trusted. If not, then you need to add the remote computer to the list of trusted computers, either by its name or by computer name (which is quite seriously complicated in the context of the Global Network).

winrm set winrm/config/client @(TrustedHosts="name or IP address of the remote computer")

This command must be used on a remote computer, specifying the address of the computer from which commands will be sent for execution.

Remote control using Windows Remote Management

Well, it’s finally time to get acquainted with the remote control commands themselves. In a command line environment, this is possible with the command

winrs

and in the Power Shell environment - the command

You can see the syntax of these commands in the environments themselves if you call help on these commands. I will give only a general view of such commands:

icm computer_name (any command)
winrs -r: Computer_name -u: User_name Any_command

I hope you understand that computer_name, Username And any_command must be replaced with variables that correspond to your wishes. And here you need to take into account the fact that this same command must belong to the shell in which the remote control takes place.