- Установка OpenSSH для Windows Server 2019 и Windows 10 Installation of OpenSSH For Windows Server 2019 and Windows 10
- Установка OpenSSH через пользовательский интерфейс настройки в Windows Server 2019 или Windows 10 версии 1809 Installing OpenSSH from the Settings UI on Windows Server 2019 or Windows 10 1809
- Установка OpenSSH с помощью PowerShell Installing OpenSSH with PowerShell
- Удаление OpenSSH Uninstalling OpenSSH
- Начальная настройка сервера SSH Initial Configuration of SSH Server
- Начальное использование SSH Initial use of SSH
- Как создать SSH ключи на Windows?
- Создание ключа
- Установка ключа
- OpenSSH Server Configuration for Windows 10 1809 and Server 2019
- Configuring the default shell for OpenSSH in Windows
- Windows Configurations in sshd_config
- AllowGroups, AllowUsers, DenyGroups, DenyUsers
- AuthenticationMethods
- AuthorizedKeysFile
- ChrootDirectory (Support added in v7.7.0.0)
- HostKey
- Match
- PermitRootLogin
- SyslogFacility
- Not supported
Установка OpenSSH для Windows Server 2019 и Windows 10 Installation of OpenSSH For Windows Server 2019 and Windows 10
Клиент OpenSSH и сервер OpenSSH являются отдельными устанавливаемыми компонентами в Windows Server 2019 и Windows 10 1809. The OpenSSH Client and OpenSSH Server are separately installable components in Windows Server 2019 and Windows 10 1809. Пользователи с этими версиями Windows могут установить и настроить OpenSSH, используя приведенные ниже инструкции. Users with these Windows versions should use the instructions that follow to install and configure OpenSSH.
Пользователи, которые получили OpenSSH из репозитория PowerShell на сайте GitHub (https://github.com/PowerShell/OpenSSH-Portable) должны использовать инструкции из репозитория, а не эти инструкции. Users who acquired OpenSSH from the PowerShell GitHub repo (https://github.com/PowerShell/OpenSSH-Portable) should use the instructions from there, and should not use these instructions.
Установка OpenSSH через пользовательский интерфейс настройки в Windows Server 2019 или Windows 10 версии 1809 Installing OpenSSH from the Settings UI on Windows Server 2019 or Windows 10 1809
Клиент и сервер OpenSSH устанавливаются в Windows 10 версии 1809 как отдельные компоненты. OpenSSH client and server are installable features of Windows 10 1809.
Чтобы установить OpenSSH, откройте раздел Параметры и последовательно выберите Приложения > Приложения и возможности > Управление дополнительными компонентами. To install OpenSSH, start Settings then go to Apps > Apps and Features > Manage Optional Features.
Просмотрите этот список и выясните, установлен ли клиент OpenSSH. Scan this list to see if OpenSSH client is already installed. Если нет, то выберите пункт Добавить компонент в верхней части страницы, а затем: If not, then at the top of the page select «Add a feature», then:
- чтобы установить клиент OpenSSH, найдите элемент Клиент OpenSSH и щелкните Установить; To install the OpenSSH client, locate «OpenSSH Client», then click «Install».
- чтобы установить сервер OpenSSH, найдите элемент Сервер OpenSSH и щелкните Установить. To install the OpenSSH server, locate «OpenSSH Server», then click «Install».
После завершения установки вернитесь в раздел Приложения > Приложения и возможности > Управление дополнительными компонентами, где теперь должны появиться компоненты OpenSSH. Once the installation completes, return to Apps > Apps and Features > Manage Optional Features and you should see the OpenSSH component(s) listed.
Установка сервера OpenSSH создаст и включит правило брандмауэра с именем OpenSSH-Server-in-TCP. Installing OpenSSH Server will create and enable a firewall rule named «OpenSSH-Server-In-TCP». Правило разрешает входящий трафик SSH через порт 22. This allows inbound SSH traffic on port 22.
Установка OpenSSH с помощью PowerShell Installing OpenSSH with PowerShell
Чтобы установить OpenSSH с помощью PowerShell, запустите PowerShell от имени администратора. To install OpenSSH using PowerShell, first launch PowerShell as an Administrator. Убедитесь, что функции OpenSSH доступны для установки, выполнив следующие действия. To make sure that the OpenSSH features are available for install:
Затем установите компонент сервера и (или) клиента. Then, install the server and/or client features:
Удаление OpenSSH Uninstalling OpenSSH
Чтобы удалить OpenSSH через раздел Параметры в ОС Windows, откройте этот раздел и последовательно выберите Приложения > Приложения и возможности > Управление дополнительными компонентами. To uninstall OpenSSH using the Windows Settings, start Settings then go to Apps > Apps and Features > Manage Optional Features. В списке установленных компонентов выберите компонент Клиент OpenSSH или Сервер OpenSSH и щелкните Удалить. In the list of installed features, select the OpenSSH Client or OpenSSH Server component, then select Uninstall.
Чтобы удалить OpenSSH с помощью PowerShell, выполните одну из следующих команд: To uninstall OpenSSH using PowerShell, use one of the following commands:
После удаления OpenSSH может потребоваться перезагрузка Windows, если служба использовалась в момент удаления. A Windows restart may be required after removing OpenSSH, if the service is in use at the time it was uninstalled.
Начальная настройка сервера SSH Initial Configuration of SSH Server
Чтобы настроить только что установленный сервер OpenSSH для использования в ОС Windows, запустите PowerShell от имени администратора и выполните следующие команды, чтобы запустить службу SSHD: To configure the OpenSSH server for initial use on Windows, launch PowerShell as an administrator, then run the following commands to start the SSHD service:
Начальное использование SSH Initial use of SSH
После установки сервера OpenSSH в Windows вы можете быстро проверить его работу с помощью PowerShell на любом устройстве Windows, где установлен клиент SSH. Once you have installed the OpenSSH Server on Windows, you can quickly test it using PowerShell from any Windows device with the SSH Client installed. В PowerShell запустите следующую команду: In PowerShell type the following command:
Первое подключение к любому серверу сопровождается сообщением примерно такого содержания: The first connection to any server will result in a message similar to the following:
В качестве ответа принимаются значения yes (да) или no (нет). The answer must be either «yes» or «no». Ответ «Да» приведет к добавлению этого сервера в список известных узлов SSH в локальной системе. Answering Yes will add that server to the local system’s list of known ssh hosts.
После этого появится запрос на ввод пароля. You will be prompted for the password at this point. В целях безопасности пароль не будет отображаться по мере ввода. As a security precaution, your password will not be displayed as you type.
После успешного подключения вы увидите командную оболочку, которая выглядит примерно так: Once you connect you will see a command shell prompt similar to the following:
По умолчанию для сервера OpenSSH в ОС Windows используется командная оболочка Windows. The default shell used by Windows OpenSSH server is the Windows command shell.
Как создать SSH ключи на Windows?
Создание ключа
Для создания ключа в ОС Windows мы будем использовать утилиту PuTTYgen.
Она устанавливается как часть стандартной установки пакета PuTTY.msi
Нет необходимости в отдельной загрузке PuTTYgen
Загрузите установочный пакет PuTTY https://putty.org и установите весь пакет.
Перейдите в меню «Пуск» —> «Все программы» —> «PuTTYgen«
Чтобы создать новую пару ключей, выберите тип ключа для генерации из нижней части экрана
(с использованием SSH-2 RSA с размером ключа 2048 бит подходит для большинства людей, другой хорошей общеизвестной альтернативой является ECDSA).
Затем нажмите «Generate» и начните перемещать курсор в окне на пустом поле.
Putty использует движения мыши для генерации случайных значений.
Точный способ перемещения мыши не может быть предсказан внешним злоумышленником.
Вам потребуется подвигать мышью в течение некоторого времени, в зависимости от размера вашего ключа. Когда вы ее перемещаете, зеленый индикатор прогресса должен продвигаться вперед.
Как только индикатор выполнения будет заполнен, произойдет фактическое вычисление генерации ключа.
По завершении открытый ключ (public key) должен появиться в окне.
Теперь вы можете указать фразу пароль для ключа (можно не указывать).
Вам необходимо сохранить хотя бы закрытый ключ (privat key), нажав «Save private key«.
К серверам OpenSSH доступ к учетной записи предоставляется путем добавления открытого ключа (public key) в файл
/.ssh /authorized_keys на сервере.
Установка ключа
Чтобы установить открытый ключ (public key), подключитесь к серверу, отредактируйте файл authorized_keys Вашим любимым редактором и вырежьте и вставьте вывод открытого ключа в файл authorized_keys. Сохраните файл.
Теперь осталось добавить наш приватный ключ (Privat key) в ssh-agent’a «Pageant» («Пуск» —> «PuTTY» —> «Pageant«).
Pageant приложение, входящее в дистрибутив PuTTY.
Это программное обеспечение используется для хранения приватных ключей в памяти в раскодированном виде, которые используются при запросе удаленного сервера.
Для того, чтобы добавить созданный ранее приватный ключ, требуется запустить Pageant, вызывать его из системного трея правой кнопкой мыши и в появившемся меню выбрать пункт «Add key«.
После того, как ключ выбран, может появится окно ввода пароля, который был добавлен при создании ключа для увеличения безопасности.
Далее, все загруженные ключи доступны в списке ключей (пункт меню View Keys):
Теперь логинимся в PuTTY.
Если Вы сделали всё правильно, то увидите сообщение:
OpenSSH Server Configuration for Windows 10 1809 and Server 2019
This topic covers the Windows-specific configuration for OpenSSH Server (sshd).
OpenSSH maintains detailed documentation for configuration options online at OpenSSH.com, which is not duplicated in this documentation set.
Configuring the default shell for OpenSSH in Windows
The default command shell provides the experience a user sees when connecting to the server using SSH. The initial default Windows is the Windows Command shell (cmd.exe). Windows also includes PowerShell and Bash, and third party command shells are also available for Windows and may be configured as the default shell for a server.
To set the default command shell, first confirm that the OpenSSH installation folder is on the system path. For Windows, the default installation folder is SystemDrive:WindowsDirectory\System32\openssh. The following commands shows the current path setting, and add the default OpenSSH installation folder to it.
Command shell | Command to use |
---|---|
Command | path |
PowerShell | $env:path |
Configuring the default ssh shell is done in the Windows registry by adding the full path to the shell executable to Computer\HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH in the string value DefaultShell.
As an example, the following Powershell command sets the default shell to be PowerShell.exe:
Windows Configurations in sshd_config
In Windows, sshd reads configuration data from %programdata%\ssh\sshd_config by default, or a different configuration file may be specified by launching sshd.exe with the -f parameter. If the file is absent, sshd generates one with the default configuration when the service is started.
The elements listed below provide Windows-specific configuration possible through entries in sshd_config. There are other configuration settings possible in that are not listed here, as they are covered in detail in the online Win32 OpenSSH documentation.
AllowGroups, AllowUsers, DenyGroups, DenyUsers
Controlling which users and groups can connect to the server is done using the AllowGroups, AllowUsers, DenyGroups and DenyUsers directives. The allow/deny directives are processed in the following order: DenyUsers, AllowUsers, DenyGroups, and finally AllowGroups. All account names must be specified in lower case. See PATTERNS in ssh_config for more information on patterns for wildcards.
When configuring user/group based rules with a domain user or group, use the following format: user?domain* . Windows allows multiple of formats for specifying domain principals, but many conflict with standard Linux patterns. For that reason, * is added to cover FQDNs. Also, this approach uses «?», instead of @, to avoid conflicts with the username@host format.
Work group users/groups and internet-connected accounts are always resolved to their local account name (no domain part, similar to standard Unix names). Domain users and groups are strictly resolved to NameSamCompatible format — domain_short_name\user_name. All user/group based configuration rules need to adhere to this format.
Examples for domain users and groups
Examples for local users and groups
AuthenticationMethods
For Windows OpenSSH, the only available authentication methods are «password» and «publickey».
AuthorizedKeysFile
The default is «.ssh/authorized_keys .ssh/authorized_keys2». If the path is not absolute, it is taken relative to user’s home directory (or profile image path). Ex. c:\users\user. Note that if the user belongs to the administrator group, %programdata%/ssh/administrators_authorized_keys is used instead.
ChrootDirectory (Support added in v7.7.0.0)
This directive is only supported with sftp sessions. A remote session into cmd.exe wouldn’t honor this. To setup a sftp-only chroot server, set ForceCommand to internal-sftp. You may also set up scp with chroot, by implementing a custom shell that would only allow scp and sftp.
HostKey
The defaults are %programdata%/ssh/ssh_host_ecdsa_key, %programdata%/ssh/ssh_host_ed25519_key, %programdata%/ssh/ssh_host_dsa_key, and %programdata%/ssh/ssh_host_rsa_key. If the defaults are not present, sshd automatically generates these on a service start.
Match
Note that pattern rules in this section. User and group names should be in lower case.
PermitRootLogin
Not applicable in Windows. To prevent administrator login, use Administrators with DenyGroups directive.
SyslogFacility
If you need file based logging, use LOCAL0. Logs are generated under %programdata%\ssh\logs. For any other value, including the default value, AUTH directs logging to ETW. For more info, see Logging Facilities in Windows.
Not supported
The following configuration options are not available in the OpenSSH version that ships in Windows Server 2019 and Windows 10 1809:
- AcceptEnv
- AllowStreamLocalForwarding
- AuthorizedKeysCommand
- AuthorizedKeysCommandUser
- AuthorizedPrincipalsCommand
- AuthorizedPrincipalsCommandUser
- Compression
- ExposeAuthInfo
- GSSAPIAuthentication
- GSSAPICleanupCredentials
- GSSAPIStrictAcceptorCheck
- HostbasedAcceptedKeyTypes
- HostbasedAuthentication
- HostbasedUsesNameFromPacketOnly
- IgnoreRhosts
- IgnoreUserKnownHosts
- KbdInteractiveAuthentication
- KerberosAuthentication
- KerberosGetAFSToken
- KerberosOrLocalPasswd
- KerberosTicketCleanup
- PermitTunnel
- PermitUserEnvironment
- PermitUserRC
- PidFile
- PrintLastLog
- RDomain
- StreamLocalBindMask
- StreamLocalBindUnlink
- StrictModes
- X11DisplayOffset
- X11Forwarding
- X11UseLocalhost
- XAuthLocation
—>