What is windows powershell remoting

Выполнение удаленных команд Running Remote Commands

Одна команда Windows PowerShell позволяет запускать команды на одном или сотнях компьютеров. You can run commands on one or hundreds of computers with a single PowerShell command. Windows PowerShell поддерживает удаленное вычисление с помощью разных технологий, включая WMI, RPC и WS-Management. Windows PowerShell supports remote computing by using various technologies, including WMI, RPC, and WS-Management.

PowerShell Core поддерживает инструментарий WMI, WS-Management и удаленное взаимодействие через SSH. PowerShell Core supports WMI, WS-Management, and SSH remoting. В PowerShell 6 RPC больше не поддерживается. In PowerShell 6, RPC is no longer supported. В PowerShell 7 и более поздних версиях RPC поддерживается только в Windows. In PowerShell 7 and above, RPC is supported only in Windows.

Дополнительные сведения об удаленном взаимодействии в PowerShell Core см. в следующих статьях: For more information about remoting in PowerShell Core, see the following articles:

Удаленное взаимодействие с Windows PowerShell без настройки Windows PowerShell Remoting Without Configuration

Многие командлеты Windows PowerShell имеют параметр ComputerName, который позволяет собирать данные и изменять параметры одного или нескольких удаленных компьютеров. Many Windows PowerShell cmdlets have the ComputerName parameter that enables you to collect data and change settings on one or more remote computers. Эти командлеты используют разные протоколы связи и работают во всех операционных системах Windows без специальной настройки. These cmdlets use varying communication protocols and work on all Windows operating systems without any special configuration.

В эти командлеты входят следующие: These cmdlets include:

Обычно командлеты, которые поддерживают удаленное взаимодействие без специальной настройки, имеют параметр ComputerName, но не имеют параметра Session. Typically, cmdlets that support remoting without special configuration have the ComputerName parameter and don’t have the Session parameter. Чтобы найти эти командлеты в сеансе, введите: To find these cmdlets in your session, type:

Служба удаленного взаимодействия Windows PowerShell Windows PowerShell Remoting

Благодаря использованию протокола WS-Management служба удаленного взаимодействия Windows PowerShell позволяет запустить любую команду Windows PowerShell на одном или нескольких удаленных компьютерах. Using the WS-Management protocol, Windows PowerShell remoting lets you run any Windows PowerShell command on one or more remote computers. Вы можете устанавливать постоянные подключения, запускать интерактивные сеансы и выполнять скрипты на удаленных компьютерах. You can establish persistent connections, start interactive sessions, and run scripts on remote computers.

Чтобы использовать службу удаленного взаимодействия Windows PowerShell, удаленный компьютер должен быть настроен для удаленного управления. To use Windows PowerShell remoting, the remote computer must be configured for remote management. Дополнительные сведения, в том числе инструкции, см. в разделе about_Remote_Requirements. For more information, including instructions, see About Remote Requirements.

После настройки службы удаленного взаимодействия Windows PowerShell вы получите доступ ко многим стратегиям удаленного взаимодействия. Once you have configured Windows PowerShell remoting, many remoting strategies are available to you. В этой статье перечислены только некоторые из них. This article lists just a few of them. См. дополнительные сведения об удаленном взаимодействии. For more information, see About Remote.

Запуск интерактивного сеанса Start an Interactive Session

Чтобы запустить интерактивный сеанс с одним удаленным компьютером, используйте командлет Enter-PSSession. To start an interactive session with a single remote computer, use the Enter-PSSession cmdlet. Например, чтобы запустить интерактивный сеанс с удаленным компьютером Server01, введите: For example, to start an interactive session with the Server01 remote computer, type:

Читайте также:  Windows powershell удалить файлы

В командной строке отобразится имя удаленного компьютера. The command prompt changes to display the name of the remote computer. Все команды, введенные в командной строке, запускаются на удаленном компьютере, а результаты отображаются на локальном компьютере. Any commands that you type at the prompt run on the remote computer and the results are displayed on the local computer.

Чтобы завершить интерактивный сеанс, введите: To end the interactive session, type:

См. дополнительные сведения о командлетах Enter-PSSession и Exit-PSSession: For more information about the Enter-PSSession and Exit-PSSession cmdlets, see:

Выполнение удаленной команды Run a Remote Command

Чтобы выполнить команду на одном или нескольких компьютерах, используйте командлет Invoke-Command. To run a command on one or more computers, use the Invoke-Command cmdlet. Например, чтобы выполнить команду Get-UICulture на удаленных компьютерах Server01 и Server02, введите: For example, to run a Get-UICulture command on the Server01 and Server02 remote computers, type:

Выходные данные будут возвращены на ваш компьютер. The output is returned to your computer.

Запуск сценария Run a Script

Чтобы запустить скрипт на одном или нескольких удаленных компьютерах, используйте параметр FilePath командлета Invoke-Command . To run a script on one or many remote computers, use the FilePath parameter of the Invoke-Command cmdlet. Сценарий должен быть включен или доступен для локального компьютера. The script must be on or accessible to your local computer. Результаты будут возвращены на локальный компьютер. The results are returned to your local computer.

Например, следующая команда выполняет скрипт DiskCollect.ps1 на удаленных компьютерах Server01 и Server02. For example, the following command runs the DiskCollect.ps1 script on the remote computers, Server01 and Server02.

Установка постоянного подключения Establish a Persistent Connection

Используйте командлет New-PSSession для создания постоянного сеанса на удаленном компьютере. Use the New-PSSession cmdlet to create a persistent session on a remote computer. В следующем примере создаются удаленные сеансы на удаленных компьютерах Server01 и Server02. The following example creates remote sessions on Server01 and Server02. Объекты сеанса хранятся в переменной $s . The session objects are stored in the $s variable.

После установки сеансов в них можно выполнить любую команду. Now that the sessions are established, you can run any command in them. Так как сеансы являются постоянными, вы можете собирать данные из одной команды и использовать их в другой. And because the sessions are persistent, you can collect data from one command and use it in another command.

Например, следующая команда выполняет команду Get-Hotfix в сеансах в переменной $s и сохраняет результаты в переменной $h. For example, the following command runs a Get-HotFix command in the sessions in the $s variable and it saves the results in the $h variable. Переменная $h создается в каждом сеансе в переменной $s, но она не существует в локальном сеансе. The $h variable is created in each of the sessions in $s, but it doesn’t exist in the local session.

Теперь вы можете использовать данные в переменной $h с другими командами в том же сеансе. Now you can use the data in the $h variable with other commands in the same session. Результаты отобразятся на локальном компьютере. The results are displayed on the local computer. Пример: For example:

Расширенная служба удаленного взаимодействия Advanced Remoting

Это и есть служба удаленного взаимодействия Windows PowerShell. Windows PowerShell remote management just begins here. Используя командлеты, установленные с Windows PowerShell, можно установить и настроить удаленные сеансы с локальных и удаленных компьютеров, создать настраиваемые и ограниченные сеансы, разрешить пользователям импортировать команды из удаленного сеанса, которые могут неявно выполняться в удаленном сеансе, настроить безопасность удаленного сеанса и многое другое. By using the cmdlets installed with Windows PowerShell, you can establish and configure remote sessions both from the local and remote ends, create customized and restricted sessions, allow users to import commands from a remote session that actually run implicitly on the remote session, configure the security of a remote session, and much more.

Читайте также:  Windows driver foundation грузит процессор windows

Windows PowerShell включает поставщик WSMan. Windows PowerShell includes a WSMan provider. Поставщик создает диск WSMAN: , который позволяет перемещаться по иерархии параметров конфигурации на локальном и удаленном компьютерах. The provider creates a WSMAN: drive that lets you navigate through a hierarchy of configuration settings on the local computer and remote computers.

См. дополнительные сведения о поставщике WSMan и командлетах WS-Management или введите команду Get-Help wsman в консоли Windows PowerShell. For more information about the WSMan provider, see WSMan Provider and About WS-Management Cmdlets, or in the Windows PowerShell console, type Get-Help wsman .

Дополнительные сведения можно найти в разделе For more information, see:

Справку по ошибкам службы удаленного взаимодействия см. в разделе about_Remote_Troubleshooting. For help with remoting errors, see about_Remote_Troubleshooting.

PowerShell remoting over SSH

Overview

PowerShell remoting normally uses WinRM for connection negotiation and data transport. SSH is now available for Linux and Windows platforms and allows true multiplatform PowerShell remoting.

WinRM provides a robust hosting model for PowerShell remote sessions. SSH-based remoting doesn’t currently support remote endpoint configuration and Just Enough Administration (JEA).

SSH remoting lets you do basic PowerShell session remoting between Windows and Linux computers. SSH remoting creates a PowerShell host process on the target computer as an SSH subsystem. Eventually we’ll implement a general hosting model, similar to WinRM, to support endpoint configuration and JEA.

The New-PSSession , Enter-PSSession , and Invoke-Command cmdlets now have a new parameter set to support this new remoting connection.

To create a remote session, you specify the target computer with the HostName parameter and provide the user name with UserName. When running the cmdlets interactively, you’re prompted for a password. You can also use SSH key authentication using a private key file with the KeyFilePath parameter. Creating keys for SSH authentication varies by platform.

General setup information

PowerShell 6 or higher, and SSH must be installed on all computers. Install both the SSH client ( ssh.exe ) and server ( sshd.exe ) so that you can remote to and from the computers. OpenSSH for Windows is now available in Windows 10 build 1809 and Windows Server 2019. For more information, see Manage Windows with OpenSSH. For Linux, install SSH, including sshd server, that’s appropriate for your platform. You also need to install PowerShell from GitHub to get the SSH remoting feature. The SSH server must be configured to create an SSH subsystem to host a PowerShell process on the remote computer. And, you must enable password or key-based authentication.

Set up on a Windows computer

Install the latest version of PowerShell. For more information, see Installing PowerShell Core on Windows.

You can confirm that PowerShell has SSH remoting support by listing the New-PSSession parameter sets. You’ll notice there are parameter set names that begin with SSH. Those parameter sets include SSH parameters.

Install the latest Win32 OpenSSH. For installation instructions, see Getting started with OpenSSH.

If you want to set PowerShell as the default shell for OpenSSH, see Configuring Windows for OpenSSH.

Edit the sshd_config file located at $env:ProgramData\ssh .

Make sure password authentication is enabled:

Create the SSH subsystem that hosts a PowerShell process on the remote computer:

The default location of the PowerShell executable is c:/progra

1/powershell/7/pwsh.exe . The location can vary depending on how you installed PowerShell.

Читайте также:  Linux hard drive driven

You must use the 8.3 short name for any file paths that contain spaces. There’s a bug in OpenSSH for Windows that prevents spaces from working in subsystem executable paths. For more information, see this GitHub issue.

The 8.3 short name for the Program Files folder in Windows is usually Progra

1 . However, you can use the following command to make sure:

Optionally, enable key authentication:

Restart the sshd service.

Add the path where OpenSSH is installed to your Path environment variable. For example, C:\Program Files\OpenSSH\ . This entry allows for the ssh.exe to be found.

Set up on an Ubuntu 16.04 Linux computer

Install the latest version of PowerShell, see Installing PowerShell Core on Linux.

Edit the sshd_config file at location /etc/ssh .

Make sure password authentication is enabled:

Optionally, enable key authentication:

For more information about creating SSH keys on Ubuntu, see the manpage for ssh-keygen.

Add a PowerShell subsystem entry:

The default location of the PowerShell executable is /usr/bin/pwsh . The location can vary depending on how you installed PowerShell.

Optionally, enable key authentication:

Restart the ssh service.

Set up on a macOS computer

Install the latest version of PowerShell. For more information, Installing PowerShell Core on macOS.

Make sure SSH Remoting is enabled by following these steps:

  1. Open System Preferences .
  2. Click on Sharing .
  3. Check Remote Login to set Remote Login: On .
  4. Allow access to the appropriate users.

Edit the sshd_config file at location /private/etc/ssh/sshd_config .

Use a text editor such as nano:

Make sure password authentication is enabled:

Add a PowerShell subsystem entry:

The default location of the PowerShell executable is /usr/local/bin/pwsh . The location can vary depending on how you installed PowerShell.

Optionally, enable key authentication:

Restart the sshd service.

Authentication

PowerShell remoting over SSH relies on the authentication exchange between the SSH client and SSH service and doesn’t implement any authentication schemes itself. The result is that any configured authentication schemes including multi-factor authentication are handled by SSH and independent of PowerShell. For example, you can configure the SSH service to require public key authentication and a one-time password for added security. Configuration of multi-factor authentication is outside the scope of this documentation. Refer to documentation for SSH on how to correctly configure multi-factor authentication and validate it works outside of PowerShell before attempting to use it with PowerShell remoting.

Users retain the same privileges in remote sessions. Meaning, Administrators have access to an elevated shell, and normal users will not.

PowerShell remoting example

The easiest way to test remoting is to try it on a single computer. In this example, we create a remote session back to the same Linux computer. We’re using PowerShell cmdlets interactively so we see prompts from SSH asking to verify the host computer and prompting for a password. You can do the same thing on a Windows computer to ensure remoting is working. Then, remote between computers by changing the host name.

Limitations

The sudo command doesn’t work in a remote session to a Linux computer.

PSRemoting over SSH does not support Profiles and does not have access to $PROFILE . Once in a session, you can load a profile by dot sourcing the profile with the full filepath. This is not related to SSH profiles. You can configure the SSH server to use PowerShell as the default shell and to load a profile through SSH. See the SSH documentation for more information.

Prior to PowerShell 7.1, remoting over SSH did not support second-hop remote sessions. This capability was limited to sessions using WinRM. PowerShell 7.1 allows Enter-PSSession and Enter-PSHostProcess to work from within any interactive remote session.

Оцените статью