Installing ssh server windows

Содержание
  1. Install OpenSSH
  2. Install OpenSSH using Windows Settings
  3. Install OpenSSH using PowerShell
  4. Start and configure SSH Server
  5. Connect to SSH Server
  6. Uninstall OpenSSH using Windows Settings
  7. Uninstall OpenSSH using PowerShell
  8. Installing SFTP/SSH Server on Windows using OpenSSH
  9. Installing SFTP/SSH Server
  10. On Windows 10 version 1803 and newer
  11. On earlier versions of Windows
  12. Configuring SSH server
  13. Setting up SSH public key authentication
  14. Connecting to the server
  15. Finding Host Key
  16. Connecting
  17. OpenSSH Server Configuration for Windows 10 1809 and Server 2019
  18. Configuring the default shell for OpenSSH in Windows
  19. Windows Configurations in sshd_config
  20. AllowGroups, AllowUsers, DenyGroups, DenyUsers
  21. AuthenticationMethods
  22. AuthorizedKeysFile
  23. ChrootDirectory (Support added in v7.7.0.0)
  24. HostKey
  25. Match
  26. PermitRootLogin
  27. SyslogFacility
  28. Not supported
  29. Конфигурация сервера OpenSSH для Windows 10 версии 1809 и Windows Server 2019 OpenSSH Server Configuration for Windows 10 1809 and Server 2019
  30. Настройка стандартной оболочки OpenSSH для Windows Configuring the default shell for OpenSSH in Windows
  31. Конфигурация Windows в файле sshd_config Windows Configurations in sshd_config
  32. AllowGroups, AllowUsers, DenyGroups, DenyUsers AllowGroups, AllowUsers, DenyGroups, DenyUsers
  33. AuthenticationMethods AuthenticationMethods
  34. AuthorizedKeysFile AuthorizedKeysFile
  35. ChrootDirectory (добавлена поддержка в версии 7.7.0.0) ChrootDirectory (Support added in v7.7.0.0)
  36. HostKey HostKey
  37. Сопоставление Match
  38. PermitRootLogin PermitRootLogin
  39. SyslogFacility SyslogFacility
  40. Не поддерживается Not supported

Install OpenSSH

Applies to Windows Server 2019, Windows 10

OpenSSH is a connectivity tool for remote login that uses the SSH protocol. It encrypts all traffic between client and server to eliminate eavesdropping, connection hijacking, and other attacks.

OpenSSH can be used to connect Window 10 clients to Windows Server 2019. OpenSSH Client is available to install on Windows 10 build 1809 and later, while OpenSSH Server is available to install on Windows Server 2019 and later.

If you downloaded OpenSSH from the GitHub repo at PowerShell/openssh-portable, follow the instructions listed there, not the ones in this article.

Install OpenSSH using Windows Settings

Both OpenSSH components can be installed using Windows Settings. OpenSSH Server is installed on Windows Server and OpenSSH Client is installed on Windows 10 devices.

To install the OpenSSH components:

Open Settings, select Apps > Apps & Features, then select Optional Features.

Scan the list to see if the OpenSSH is already installed. If not, at the top of the page, select Add a feature, then:

  • On Windows 10, find OpenSSH Client, then click Install
  • On Windows Server 2019, find OpenSSH Server, then click Install

Once setup completes, return to Apps > Apps & Features and Optional Features and you should see OpenSSH listed.

Installing OpenSSH Server will create and enable a firewall rule named OpenSSH-Server-In-TCP . This allows inbound SSH traffic on port 22. If this rule is not enabled and this port is not open, connections will be refused or reset.

Install OpenSSH using PowerShell

To install OpenSSH using PowerShell, run PowerShell as an Administrator. To make sure that OpenSSH is available, run the following cmdlet:

This should return the following output:

Then, install the server or client components as needed:

Both of these should return the following output:

Start and configure SSH Server

To start and configure OpenSSH server for initial use, open PowerShell as an administrator, then run the following commands to start the SSHD service :

Connect to SSH Server

Once installed, you can connect to OpenSSH Server from a Windows 10 device with the SSH client installed using PowerShell as follows. Be sure to run PowerShell as an administrator:

Once connected, you get a message similar to the following:

Selecting yes adds that server to the list of known ssh hosts on your Windows client.

You are prompted for the password at this point. As a security precaution, your password will not be displayed as you type.

Once connected, you will see the Windows command shell prompt:

Uninstall OpenSSH using Windows Settings

To uninstall OpenSSH using Windows Settings:

  1. Open Settings, then go to Apps > Apps & Features.
  2. Go to Optional Features.
  3. In the list, select OpenSSH Client or OpenSSH Server.
  4. Select Uninstall.

Uninstall OpenSSH using PowerShell

To uninstall the OpenSSH components using PowerShell, use the following commands:

You may need to restart Windows afterwards if the service was in use at the time it was uninstalled.

Installing SFTP/SSH Server on Windows using OpenSSH

Recently, Microsoft has released a port of OpenSSH for Windows. You can use the package to set up an SFTP /SSH server on Windows.

Installing SFTP/SSH Server

On Windows 10 version 1803 and newer

  • In Settings app, go to Apps > Apps & features > Manage optional features.
  • Locate “OpenSSH server” feature, expand it, and select Install.

Binaries are installed to %WINDIR%\System32\OpenSSH . Configuration file ( sshd_config ) and host keys are installed to %ProgramData%\ssh (only after the server is started for the first time).

You may still want to use the following manual installation, if you want to install a newer version of OpenSSH than the one built into Windows 10.

On earlier versions of Windows

  • Download the latest OpenSSH for Windows binaries (package OpenSSH-Win64.zip or OpenSSH-Win32.zip )
  • As the Administrator, extract the package to C:\Program Files\OpenSSH
  • As the Administrator, install sshd and ssh-agent services:

Configuring SSH server

  • Allow incoming connections to SSH server in Windows Firewall:
    • When installed as an optional feature, the firewall rule “OpenSSH SSH Server (sshd)” should have been created automatically. If not, proceed to create and enable the rule as follows.
    • Either run the following PowerShell command as the Administrator:
      Replace C:\System32\OpenSSH\sshd.exe with the actual path to the sshd.exe ( C:\Program Files\OpenSSH\ssh.exe , had you followed the manual installation instructions above).
    • or go to Control Panel > System and Security > Windows Defender Firewall1> Advanced Settings > Inbound Rules and add a new rule for port 22.
  • Start the service and/or configure automatic start:
    • Go to Control Panel > System and Security > Administrative Tools and open Services. Locate OpenSSH SSH Server service.
    • If you want the server to start automatically when your machine is started: Go to Action > Properties. In the Properties dialog, change Startup type to Automatic and confirm.
    • Start the OpenSSH SSH Server service by clicking the Start the service.

Setting up SSH public key authentication

Follow a generic guide for Setting up SSH public key authentication in *nix OpenSSH server, with the following difference:

Читайте также:  Linux как редактировать ссылку

Connecting to the server

Finding Host Key

Before the first connection, find out fingerprint of the server’s host key by using ssh-keygen.exe for each file.

In Windows command-prompt, use:

Replace %WINDIR%\System32 with %ProgramFiles% , if appropriate.

In PowerShell, use:

Replace $env:WINDIR\System32 with $env:ProgramFiles , if appropriate.

You will get an output like this:

Connecting

Start WinSCP. Login dialog will appear. On the dialog:

  • Make sure New site node is selected.
  • On New site node, make sure the SFTP protocol is selected.
  • Enter your machine/server IP address (or a hostname) into the Host name box.
  • Enter your Windows account name to the User name box. It might have to be entered in the format user@domain , if running on a domain.
  • For a public key authentication:
    • Press the Advanced button to open Advanced site settings dialog and go to SSH > Authentication page.
    • In Private key file box select your private key file.
    • Submit Advanced site settings dialog with the OK button.
  • For a password authentication:
    • Enter your Windows account password to the Password box.
    • If you Windows account does not have a password, you cannot authenticate with the password authentication (i.e. with an empty password), you need to use the public key authentication.
  • Save your site settings using the Save button.
  • Login using Login button.
  • Verify the host key by comparing fingerprint with those collected before (see above).

If you cannot authenticate to the server, and you are using Windows 10 Developer mode, make sure that your OpenSSH server does not conflict with an internal SSH server used by the Developer mode. You may need to turn off the SSH Server Broker and SSH Server Proxy Windows services. Or run your OpenSSH server on a different port than 22.

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

—>

Конфигурация сервера OpenSSH для Windows 10 версии 1809 и Windows Server 2019 OpenSSH Server Configuration for Windows 10 1809 and Server 2019

В этой статье описывается настройка сервера OpenSSH (sshd) для ОС Windows. This topic covers the Windows-specific configuration for OpenSSH Server (sshd).

Для OpenSSH предоставляется подробная документация по параметрам конфигурации на веб-сайте OpenSSH.com, и мы не намерены дублировать ее в этом пакете документации. OpenSSH maintains detailed documentation for configuration options online at OpenSSH.com, which is not duplicated in this documentation set.

Настройка стандартной оболочки OpenSSH для Windows Configuring the default shell for OpenSSH in Windows

Стандартная оболочка командной строки предоставляет пользователю интерфейс, который он увидит при подключении к серверу по протоколу SSH. The default command shell provides the experience a user sees when connecting to the server using SSH. По умолчанию в среде Windows изначально используется командная оболочка Windows (cmd.exe). The initial default Windows is the Windows Command shell (cmd.exe). Кроме того, Windows включает PowerShell и Bash, и вы можете настроить в качестве оболочки по умолчанию для сервера любую из оболочек командной строки сторонних производителей, которые предоставляются для Windows. 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.

Чтобы задать командную оболочку по умолчанию, для начала убедитесь, что папка установки OpenSSH находится в системном пути. To set the default command shell, first confirm that the OpenSSH installation folder is on the system path. В среде Windows по умолчанию она устанавливается в папку SystemDrive:WindowsDirectory\System32\openssh. For Windows, the default installation folder is SystemDrive:WindowsDirectory\System32\openssh. Следующие команды позволяют узнать текущее значение пути (переменную среды path) и добавить к нему стандартную папку установки 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 PowerShell $env:path $env:path

Настройка оболочки SSH по умолчанию выполняется в реестре Windows, где вам нужно добавить полный путь к исполняемому файлу оболочки в строковое значение DefaultShell в разделе Computer\HKEY_LOCAL_MACHINE\SOFTWARE\OpenSSH. 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.

Например, следующая команда PowerShell устанавливает PowerShell.exe в качестве оболочки по умолчанию: As an example, the following Powershell command sets the default shell to be PowerShell.exe:

Конфигурация Windows в файле sshd_config Windows Configurations in sshd_config

В среде Windows программа sshd по умолчанию считывает данные конфигурации из файла %programdata%\ssh\sshd_config, но вы можете указать другой файл конфигурации, запустив команду sshd.exe с параметром -f. 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. Если указанный файл отсутствует, sshd создаст новый файл с конфигурацией по умолчанию при запуске службы. If the file is absent, sshd generates one with the default configuration when the service is started.

Ниже перечислены элементы конфигурации специально для среды Windows, которые можно указать в sshd_config. The elements listed below provide Windows-specific configuration possible through entries in sshd_config. Существуют и другие параметры конфигурации, которые здесь не перечислены, так как они подробно описаны в документации по OpenSSH для Win32 в Интернете. 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 AllowGroups, AllowUsers, DenyGroups, DenyUsers

Управление тем, какие пользователи и группы могут подключаться к серверу, осуществляется с помощью директив AllowGroups, AllowUsers, DenyGroups и DenyUsers. Controlling which users and groups can connect to the server is done using the AllowGroups, AllowUsers, DenyGroups and DenyUsers directives. Директивы разрешения и запрета обрабатываются в следующем порядке: DenyUsers, AllowUsers, DenyGroups и наконец AllowGroups. 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. Дополнительные сведения о шаблонах с подстановочными знаками вы найдете в разделе PATTERNS непосредственно в файле ssh_config. See PATTERNS in ssh_config for more information on patterns for wildcards.

При настройке правил для пользователей и (или) групп в домене используйте следующий формат: user?domain* . When configuring user/group based rules with a domain user or group, use the following format: user?domain* . Windows поддерживает несколько форматов для указания субъектов домена, но многие из них конфликтуют со стандартными шаблонами в Linux. Windows allows multiple of formats for specifying domain principals, but many conflict with standard Linux patterns. По этой причине добавлен символ *, чтобы поддерживать полные доменные имена. For that reason, * is added to cover FQDNs. Кроме того, этот подход использует «?» вместо «@», чтобы избежать конфликтов с форматом username@host. Also, this approach uses «?», instead of @, to avoid conflicts with the username@host format.

Пользователи и группы, входящие в рабочие группы, а также подключенные к Интернету учетные записи всегда разрешаются в имена локальных учетных записей (без сегмента домена, примерно как стандартные имена в UNIX). Work group users/groups and internet-connected accounts are always resolved to their local account name (no domain part, similar to standard Unix names). Пользователи и группы домена строго разрешаются в формат NameSamCompatible, то есть «короткое_имя_домена\имя_пользователя». 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 AuthenticationMethods

Для OpenSSH в Windows поддерживаются только методы проверки подлинности «password» и «publickey». For Windows OpenSSH, the only available authentication methods are «password» and «publickey».

AuthorizedKeysFile AuthorizedKeysFile

По умолчанию используется значение .ssh/authorized_keys .ssh/authorized_keys2. 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. c:\users\user. Обратите внимание, что если пользователь входит в группу администраторов, используется %programdata%/ssh/administrators_authorized_keys. Note that if the user belongs to the administrator group, %programdata%/ssh/administrators_authorized_keys is used instead.

ChrootDirectory (добавлена поддержка в версии 7.7.0.0) ChrootDirectory (Support added in v7.7.0.0)

Эта директива поддерживается только для сеансов SFTP. This directive is only supported with sftp sessions. Удаленный сеанс подключения к cmd.exe не учитывает ее. A remote session into cmd.exe wouldn’t honor this. Чтобы настроить сервер chroot только для SFTP, укажите параметр ForceCommand со значением internal-sftp. To setup a sftp-only chroot server, set ForceCommand to internal-sftp. Вы также можете настроить SCP с поддержкой chroot, реализовав пользовательскую оболочку, которая допускает только SCP и SFTP. You may also set up scp with chroot, by implementing a custom shell that would only allow scp and sftp.

HostKey HostKey

По умолчанию используются значения %programdata%/ssh/ssh_host_ecdsa_key, %programdata%/ssh/ssh_host_ed25519_key, %programdata%/ssh/ssh_host_dsa_key и %programdata%/ssh/ssh_host_rsa_key. 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. Если эти файлы отсутствуют, sshd автоматически создает их при запуске службы. 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 PermitRootLogin

Неприменимо в ОС Windows. Not applicable in Windows. Чтобы предотвратить вход администратора, примените для группы Administrators директиву DenyGroups. To prevent administrator login, use Administrators with DenyGroups directive.

SyslogFacility SyslogFacility

Если вам требуется ведение журнала в файле, используйте LOCAL0. If you need file based logging, use LOCAL0. Журналы создаются в папке %programdata%\ssh\logs. Logs are generated under %programdata%\ssh\logs. Любое другое значение, включая используемое по умолчанию AUTH, направляет журналы в ETW. For any other value, including the default value, AUTH directs logging to ETW. Дополнительные сведения см. в статье о возможностях по ведению журнала в Windows. For more info, see Logging Facilities in Windows.

Не поддерживается Not supported

Следующие параметры конфигурации недоступны в версии OpenSSH, которая поставляется в составе Windows Server 2019 и Windows 10 версии 1809: The following configuration options are not available in the OpenSSH version that ships in Windows Server 2019 and Windows 10 1809:

  • AcceptEnv AcceptEnv
  • AllowStreamLocalForwarding AllowStreamLocalForwarding
  • AuthorizedKeysCommand AuthorizedKeysCommand
  • AuthorizedKeysCommandUser AuthorizedKeysCommandUser
  • AuthorizedPrincipalsCommand AuthorizedPrincipalsCommand
  • AuthorizedPrincipalsCommandUser AuthorizedPrincipalsCommandUser
  • сжатие; Compression
  • ExposeAuthInfo ExposeAuthInfo
  • GSSAPIAuthentication GSSAPIAuthentication
  • GSSAPICleanupCredentials GSSAPICleanupCredentials
  • GSSAPIStrictAcceptorCheck GSSAPIStrictAcceptorCheck
  • HostbasedAcceptedKeyTypes HostbasedAcceptedKeyTypes
  • HostbasedAuthentication HostbasedAuthentication
  • HostbasedUsesNameFromPacketOnly HostbasedUsesNameFromPacketOnly
  • IgnoreRhosts IgnoreRhosts
  • IgnoreUserKnownHosts IgnoreUserKnownHosts
  • KbdInteractiveAuthentication KbdInteractiveAuthentication
  • KerberosAuthentication KerberosAuthentication
  • KerberosGetAFSToken KerberosGetAFSToken
  • KerberosOrLocalPasswd KerberosOrLocalPasswd
  • KerberosTicketCleanup KerberosTicketCleanup
  • PermitTunnel PermitTunnel
  • PermitUserEnvironment PermitUserEnvironment
  • PermitUserRC PermitUserRC
  • PidFile PidFile
  • PrintLastLog PrintLastLog
  • RDomain RDomain
  • StreamLocalBindMask StreamLocalBindMask
  • StreamLocalBindUnlink StreamLocalBindUnlink
  • StrictModes StrictModes
  • X11DisplayOffset X11DisplayOffset
  • X11Forwarding X11Forwarding
  • X11UseLocalhost X11UseLocalhost
  • XAuthLocation XAuthLocation

—>

Читайте также:  Wcf как windows служба
Оцените статью