Ssh клиент windows powershell

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.

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.

Читайте также:  Linux сброс всех сетевых настроек

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.

Использование встроенного SSH клиента в Windows 10

В Windows 10 и Windows Server 2019 появился встроенный SSH клиент, который вы можете использовать для подключения к *Nix серверам, ESXi хостам и другим устройствам по защищенному протоколу, вместо Putty, MTPuTTY или других сторонних SSH клиентов. Встроенный SSH клиент Windows основан на порте OpenSSH и предустановлен в ОС, начиная с Windows 10 1809.

Установка клиента OpenSSH в Windows 10

Клиент OpenSSH входит в состав Features on Demand Windows 10 (как и RSAT). Клиент SSH установлен по умолчанию в Windows Server 2019 и Windows 10 1809 и более новых билдах.

Проверьте, что SSH клиент установлен:

Get-WindowsCapability -Online | ? Name -like ‘OpenSSH.Client*’

В нашем примере клиент OpenSSH установлен (статус: State: Installed).

Если SSH клиент отсутствует (State: Not Present), его можно установить:

  • С помощью команды PowerShell: Add-WindowsCapability -Online -Name OpenSSH.Client*
  • С помощью DISM: dism /Online /Add-Capability /CapabilityName:OpenSSH.Client

0.0.1.0

  • Через Параметры -> Приложения -> Дополнительные возможности -> Добавить компонент. Найдите в списке Клиент OpenSSH и нажмите кнопку Установить.
  • ]Бинарные файлы OpenSSH находятся в каталоге c:\windows\system32\OpenSSH\.

    • ssh.exe – это исполняемый файл клиента SSH;
    • scp.exe – утилита для копирования файлов в SSH сессии;
    • ssh-keygen.exe – утилита для генерации ключей аутентификации;
    • ssh-agent.exe – используется для управления ключами;
    • ssh-add.exe – добавление ключа в базу ssh-агента.

    Как использовать SSH клиенте в Windows 10?

    Чтобы запустить SSH клиент, запустите командную строку PowerShell или cmd.exe . Выведите доступные параметры и синтаксис утилиты ssh.exe, набрав команду:

    ssh
    usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
    [-D [bind_address:]port] [-E log_file] [-e escape_char]
    [-F configfile] [-I pkcs11] [-i identity_file]
    [-J [user@]host[:port]] [-L address] [-l login_name] [-m mac_spec]
    [-O ctl_cmd] [-o option] [-p port] [-Q query_option] [-R address]
    [-S ctl_path] [-W host:port] [-w local_tun[:remote_tun]]
    destination [command]

    Для подключения к удаленному серверу по SSH используется команда:

    Если SSH сервер запущен на нестандартном порту, отличном от TCP/22, можно указать номер порта:

    ssh username@host -p port

    Например, чтобы подключиться к Linux хосту с IP адресом 192.168.1.202 под root, выполните:

    При первом подключении появится запрос на добавление ключа хоста в доверенные, наберите yes -> Enter (при этом отпечаток ключа хоста добавляется в файл C:\Users\username\.ssh\known_hosts).

    Затем появится запрос пароля указанной учетной записи, укажите пароль root, после чего должна открытся консоль удаленного Linux сервера (в моем примере на удаленном сервере установлен CentOS 8).

    Если вы используете SSH аутентификацию по RSA ключам (см. пример с настройкой SSH аутентификации по ключам в Windows), вы можете указать путь к файлу с закрытым ключом в клиенте SSH так:

    ssh root@192.168.1.92 -i «C:\Users\username\.ssh\id_rsa»

    Также вы можете добавить ваш закрытый ключ в SSH-Agent. Сначала нужно включить службу ssh-agent и настроить ее автозапуск:

    set-service ssh-agent StartupType ‘Automatic’
    Start-Service ssh-agent

    Добавим ваш закрытый ключ в базу ssh-agent:

    Теперь вы можете подключиться к серверу по SSH без указания пути к RSA ключу, он будет использоваться автоматически. Пароль для подключения не запрашивается (если только вы не защитили ваш RSA ключ отдельным паролем):

    Еще несколько полезных аргументов SSH:

    • -C – сжимать трафик между клиентом и сервером (полезно на медленных и нестабильных подключениях);
    • -v – вывод подробной информации обо всех действия клиента ssh;
    • -R / -L – можно использовать для проброса портов через SSH туннель.

    SCP: копирование файлов из/в Windows через SSH

    С помощью утилиты scp.exe, которая входит в состав пакета клиента SSH, вы можете скопировать файл с вашего компьютера на SSH сервер:

    scp.exe «E:\ISO\CentOS-8.1.1911-x86_64.iso» root@192.168.1.202:/home

    Можно рекурсивно скопировать все содержимое каталога:

    scp -r E:\ISO\ root@192.168.1.202:/home

    И наоборот, вы можете скопировать файл с удаленного сервера на ваш компьютер:

    scp.exe root@192.168.1.202:/home/CentOS-8.1.1911-x86_64.iso e:\tmp

    Итак, теперь вы можете прямо из Windows 10 подключаться к SSH серверам, копировать файлы с помощью scp без установки сторонних приложений и утилит.

    Удаленное взаимодействие с PowerShell через SSH PowerShell remoting over SSH

    Обзор Overview

    Функция удаленного взаимодействия PowerShell обычно использует WinRM для согласования соединения и передачи данных. PowerShell remoting normally uses WinRM for connection negotiation and data transport. Теперь протокол SSH доступен на платформах Linux и Windows, что позволяет осуществлять многоплатформенное удаленное взаимодействие с PowerShell. SSH is now available for Linux and Windows platforms and allows true multiplatform PowerShell remoting.

    Служба удаленного управления Windows обеспечивает надежную модель поддержки удаленных сеансов PowerShell. WinRM provides a robust hosting model for PowerShell remote sessions. Удаленное взаимодействие по протоколу SSH сейчас не поддерживает настройку удаленных конечных точек и функцию JEA (Just Enough Administration). SSH-based remoting doesn’t currently support remote endpoint configuration and Just Enough Administration (JEA).

    Удаленное взаимодействие по SSH позволяет осуществлять базовое удаленное взаимодействие между компьютерами с Windows и Linux в рамках сеансов PowerShell. SSH remoting lets you do basic PowerShell session remoting between Windows and Linux computers. Функция удаленного взаимодействия по SSH создает хост-процесс PowerShell на целевом компьютере в качестве подсистемы SSH. SSH remoting creates a PowerShell host process on the target computer as an SSH subsystem. Со временем для поддержки настройки удаленных конечных точек и функции JEA мы реализуем общую модель размещения, похожую на службе удаленного управления Windows. Eventually we’ll implement a general hosting model, similar to WinRM, to support endpoint configuration and JEA.

    Командлеты New-PSSession , Enter-PSSession и Invoke-Command теперь имеют набор новых параметров для поддержки этой возможности удаленного взаимодействия. The New-PSSession , Enter-PSSession , and Invoke-Command cmdlets now have a new parameter set to support this new remoting connection.

    Чтобы создать удаленный сеанс, укажите целевой компьютер с помощью параметра HostName и имя пользователя с помощью параметра UserName. 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. Вы также можете использовать проверку подлинности ключа SSH с помощью файла закрытого ключа с параметром KeyFilePath. You can also use SSH key authentication using a private key file with the KeyFilePath parameter. Способ создания ключей для проверки подлинности по протоколу SSH зависит от платформы. Creating keys for SSH authentication varies by platform.

    Общие сведения об установке General setup information

    PowerShell 6 или более поздней версии, и на всех компьютерах должен быть установлен SSH. PowerShell 6 or higher, and SSH must be installed on all computers. Установите клиент ( ssh.exe ) и сервер ( sshd.exe ) SSH, чтобы осуществлять удаленное взаимодействие между компьютерами. Install both the SSH client ( ssh.exe ) and server ( sshd.exe ) so that you can remote to and from the computers. Решение OpenSSH для Windows теперь доступно в Windows 10 сборки 1809 и Windows Server 2019. OpenSSH for Windows is now available in Windows 10 build 1809 and Windows Server 2019. Дополнительные сведения см. в статье Управление Windows через OpenSSH. For more information, see Manage Windows with OpenSSH. В Linux нужно реализовать поддержку SSH (включая установку сервера sshd) в соответствии с используемой платформой. For Linux, install SSH, including sshd server, that’s appropriate for your platform. Также для поддержки удаленного взаимодействия по SSH нужно установить PowerShell с сайта GitHub. You also need to install PowerShell from GitHub to get the SSH remoting feature. Для сервера SSH нужно настроить возможность создать подсистему SSH для размещения процесса PowerShell на удаленном компьютере. 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.

    Настройка на компьютере с Windows Set up on a Windows computer

    Установите последнюю версию PowerShell. Install the latest version of PowerShell. Дополнительные сведения см. в статье Установка PowerShell Core в Windows. For more information, see Installing PowerShell Core on Windows.

    Чтобы убедиться, что в PowerShell есть поддержка удаленного взаимодействия SSH, перечислите наборы параметров New-PSSession . You can confirm that PowerShell has SSH remoting support by listing the New-PSSession parameter sets. Обратите внимание на наличие имен наборов параметров, начинающихся с SSH. You’ll notice there are parameter set names that begin with SSH. К этим наборам параметров относятся параметры SSH. Those parameter sets include SSH parameters.

    Установите последнюю версию Win32 OpenSSH. Install the latest Win32 OpenSSH. Инструкции по установке см. в разделе Начало работы с OpenSSH. For installation instructions, see Getting started with OpenSSH.

    Если вы хотите задать PowerShell в качестве оболочки по умолчанию для OpenSSH, см. раздел Настройка Windows для OpenSSH. If you want to set PowerShell as the default shell for OpenSSH, see Configuring Windows for OpenSSH.

    Измените файл sshd_config , расположенный в $env:ProgramData\ssh . Edit the sshd_config file located at $env:ProgramData\ssh .

    Включите проверку подлинности с помощью пароля: Make sure password authentication is enabled:

    Создайте подсистему SSH, в которой размещается процесс PowerShell на удаленном компьютере: Create the SSH subsystem that hosts a PowerShell process on the remote computer:

    Расположение исполняемого файла PowerShell по умолчанию — c:/progra

    1/powershell/7/pwsh.exe . The default location of the PowerShell executable is c:/progra

    1/powershell/7/pwsh.exe . Расположение может различаться в зависимости от способа установки PowerShell. The location can vary depending on how you installed PowerShell.

    Необходимо использовать краткое имя 8.3 для всех путей к файлам, содержащим пробелы. You must use the 8.3 short name for any file paths that contain spaces. В OpenSSH для Windows обнаружена ошибка, блокирующая работу пробелов в путях к исполняемым файлам подсистемы. There’s a bug in OpenSSH for Windows that prevents spaces from working in subsystem executable paths. См. дополнительные сведения на сайте GitHub. For more information, see this GitHub issue.

    Обычно краткое имя 8.3 для папки Program Files в Windows — это Progra

    1 . 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:

    Дополнительные сведения см. в статье Управление ключами OpenSSH. For more information, see Managing OpenSSH Keys.

    Перезапустите службу sshd. Restart the sshd service.

    Добавьте путь установки OpenSSH в свою переменную среды Path. Add the path where OpenSSH is installed to your Path environment variable. Например, C:\Program Files\OpenSSH\ . For example, C:\Program Files\OpenSSH\ . Это позволит найти файл ssh.exe . This entry allows for the ssh.exe to be found.

    Настройка на компьютере с Ubuntu 16.04 Linux Set up on an Ubuntu 16.04 Linux computer

    Установите последнюю версию PowerShell, см. раздел Установка PowerShell Core в Linux. Install the latest version of PowerShell, see Installing PowerShell Core on Linux.

    Измените файл sshd_config в расположении /etc/ssh . Edit the sshd_config file at location /etc/ssh .

    Включите проверку подлинности с помощью пароля: Make sure password authentication is enabled:

    При необходимости включите проверку подлинности на основе ключа: Optionally, enable key authentication:

    Дополнительные сведения о создании ключей SSH в Ubuntu см. на странице справки по ssh-keygen. For more information about creating SSH keys on Ubuntu, see the manpage for ssh-keygen.

    Добавьте запись подсистемы PowerShell: Add a PowerShell subsystem entry:

    Расположение исполняемого файла PowerShell по умолчанию — /usr/bin/pwsh . The default location of the PowerShell executable is /usr/bin/pwsh . Расположение может различаться в зависимости от способа установки PowerShell. The location can vary depending on how you installed PowerShell.

    При необходимости включите проверку подлинности на основе ключа: Optionally, enable key authentication:

    Перезапустите службу ssh. Restart the ssh service.

    Настройка на компьютере с macOS Set up on a macOS computer

    Установите последнюю версию PowerShell. Install the latest version of PowerShell. Дополнительные сведения см. в статье Установка PowerShell Core в macOS. For more information, Installing PowerShell Core on macOS.

    Убедитесь, что удаленное взаимодействие SSH включено, выполните следующие действия: Make sure SSH Remoting is enabled by following these steps:

    1. Откройте среду System Preferences . Open System Preferences .
    2. Щелкните Sharing . Click on Sharing .
    3. Установите флажок Remote Login , чтобы задать Remote Login: On . Check Remote Login to set Remote Login: On .
    4. Разрешите доступ соответствующим пользователям. Allow access to the appropriate users.

    Измените файл sshd_config в расположении /private/etc/ssh/sshd_config . Edit the sshd_config file at location /private/etc/ssh/sshd_config .

    Используйте текстовый редактор, например nano: Use a text editor such as nano:

    Включите проверку подлинности с помощью пароля: Make sure password authentication is enabled:

    Добавьте запись подсистемы PowerShell: Add a PowerShell subsystem entry:

    Расположение исполняемого файла PowerShell по умолчанию — /usr/local/bin/pwsh . The default location of the PowerShell executable is /usr/local/bin/pwsh . Расположение может различаться в зависимости от способа установки PowerShell. The location can vary depending on how you installed PowerShell.

    При необходимости включите проверку подлинности на основе ключа: Optionally, enable key authentication:

    Перезапустите службу sshd. Restart the sshd service.

    Аутентификация Authentication

    При удаленном взаимодействии с PowerShell через SSH используется обмен данными для проверки подлинности между клиентом SSH и службой SSH. Схемы проверки подлинности в его рамках не реализуются. PowerShell remoting over SSH relies on the authentication exchange between the SSH client and SSH service and doesn’t implement any authentication schemes itself. Это означает, что любые настроенные схемы проверки подлинности, включая многофакторную проверку подлинности, обрабатываются протоколом SSH независимо от PowerShell. The result is that any configured authentication schemes including multi-factor authentication are handled by SSH and independent of PowerShell. Например, в службе SSH можно настроить обязательное применение проверки подлинности на основе открытых ключей, а также разовых паролей для усиления безопасности. 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. Сведения о том, как правильно настроить многофакторную проверку подлинности и проверить ее работу вне PowerShell, прежде чем пытаться использовать ее для удаленного взаимодействия с PowerShell, см. в документации по SSH. 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 PowerShell remoting example

    Проще всего проверить удаленное взаимодействие на одном компьютере. The easiest way to test remoting is to try it on a single computer. В этом примере мы создадим удаленный сеанс с одним и тем же компьютером Linux. In this example, we create a remote session back to the same Linux computer. Командлеты PowerShell мы выполняем в интерактивном режиме, поэтому мы увидим запрос от SSH на проверку удаленного компьютера, а также запрос на ввод пароля. We’re using PowerShell cmdlets interactively so we see prompts from SSH asking to verify the host computer and prompting for a password. Чтобы убедиться, что удаленное взаимодействие работает, те же операции можно выполнить на компьютере Windows. 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

    Команда sudo не работает в рамках сеанса удаленного взаимодействия с компьютером Linux. The sudo command doesn’t work in a remote session to a Linux computer.

    PSRemoting через SSH не поддерживает профили и не имеет доступа к $PROFILE . 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. Это не связано с профилями SSH. This is not related to SSH profiles. Вы можете настроить SSH-сервер для использования PowerShell в качестве оболочки по умолчанию и для загрузки профиля через SSH. You can configure the SSH server to use PowerShell as the default shell and to load a profile through SSH. Дополнительные сведения см. в документации по SSH. See the SSH documentation for more information.

    До PowerShell 7.1 удаленное взаимодействие по SSH не поддерживало удаленные сеансы со вторым прыжком. Prior to PowerShell 7.1, remoting over SSH did not support second-hop remote sessions. Эта возможность была ограничена сеансами через WinRM. This capability was limited to sessions using WinRM. PowerShell 7.1 позволяет Enter-PSSession и Enter-PSHostProcess работать в любом интерактивном удаленном сеансе. PowerShell 7.1 allows Enter-PSSession and Enter-PSHostProcess to work from within any interactive remote session.

    Читайте также:  Температура процессора windows норма
    Оцените статью