Windows config from run

Конфигурация сервера 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

—>

WSL commands and launch configurations

Ways to run WSL

There are several ways to run a Linux distribution with WSL once it’s installed.

  1. Open your Linux distribution by visiting the Windows Start menu and typing the name of your installed distributions. For example: «Ubuntu».
  2. From Windows Command Prompt or PowerShell, enter the name of your installed distribution. For example: ubuntu
  3. From Windows Command Prompt or PowerShell, to open your default Linux distribution inside your current command line, enter: wsl.exe .
  4. From Windows Command Prompt or PowerShell, to open your default Linux distribution inside your current command line, enter: wsl [command] .

Which method you should use depends on what you’re doing. If you’ve opened a WSL command line within a Windows Prompt or PowerShell window and want to exit, enter the command: exit .

Launch WSL by distribution

Running a distribution using it’s distro-specific application launches that distribution in it’s own console window.

It is the same as clicking «Launch» in the Microsoft store.

You can also run the distribution from the command line by running [distribution].exe .

The disadvantage of running a distribution from the command line in this way is that it will automatically change your working directory from the current directory to the distribution’s home directory.

Example: (using PowerShell)

wsl and wsl [command]

The best way to run WSL from the command line is using wsl.exe .

Example: (using PowerShell)

Not only does wsl keep the current working directory in place, it lets you run a single command along side Windows commands.

Example: (using PowerShell)

Example: (using PowerShell)

Managing multiple Linux Distributions

In Windows 10 Version 1903 and later, you can use wsl.exe to manage your distributions in the Windows Subsystem for Linux (WSL), including listing available distributions, setting a default distribution, and uninstalling distributions.

Each Linux distribution independently manages its own configurations. To see distribution-specific commands, run [distro.exe] /? . For example ubuntu /? .

List distributions

wsl -l , wsl —list
Lists available Linux distributions available to WSL. If a distribution is listed, it’s installed and ready to use.

wsl —list —all Lists all distributions, including ones that aren’t currently usable. They may be in the process of installing, uninstalling, or are in a broken state.

wsl —list —running Lists all distributions that are currently running.

Set a default distribution

The default WSL distribution is the one that runs when you run wsl on a command line.

wsl -s , wsl —setdefault

Sets the default distribution to .

Example: (using PowerShell)
wsl -s Ubuntu would set my default distribution to Ubuntu. Now when I run wsl npm init it will run in Ubuntu. If I run wsl it will open an Ubuntu session.

Unregister and reinstall a distribution

While Linux distributions can be installed through the Microsoft store, they can’t be uninstalled through the store. WSL Config allows distributions to be unregistered/uninstalled.

Unregistering also allows distributions to be reinstalled.

Caution: Once unregistered, all data, settings, and software associated with that distribution will be permanently lost. Reinstalling from the store will install a clean copy of the distribution.

wsl —unregister
Unregisters the distribution from WSL so it can be reinstalled or cleaned up.

For example: wsl —unregister Ubuntu would remove Ubuntu from the distributions available in WSL. When I run wsl —list it will not be listed.

To reinstall, find the distribution in the Microsoft store and select «Launch».

Run as a specific user

wsl -u , wsl —user

Run WSL as the specified user. Please note that user must exist inside of the WSL distribution.

Change the default user for a distribution

Change the default user that for your distribution log-in. The user has to already exist inside the distribution in order to become the default user.

For example: ubuntu config —default-user johndoe would change the default user for the Ubuntu distribution to the «johndoe» user.

If you are having trouble figuring out the name of your distribution, see List distributions for the command to list the official name of the installed distributions.

Run a specific distribution

wsl -d , wsl —distribution

Run a specified distribution of WSL, can be used to send commands to a specific distribution without having to change your default.

Managing multiple Linux Distributions in earlier Windows versions

In Windows 10 prior to version 1903, the WSL Config ( wslconfig.exe ) command-line tool should be used to manage Linux distributions running on the Windows Subsystem for Linux (WSL). It lets you list available distributions, set a default distribution, and uninstall distributions.

While WSL Config is helpful for settings that span or coordinate distributions, each Linux distribution independently manages its own configurations. To see distribution-specific commands, run [distro.exe] /? . For example ubuntu /? .

To see all available options for wslconfig, run: wslconfig /?

To list distributions, use:

wslconfig /list
Lists available Linux distributions available to WSL. If a distribution is listed, it’s installed and ready to use.

wslconfig /list /all
Lists all distributions, including ones that aren’t currently usable. They may be in the process of installing, uninstalling, or are in a broken state.

To set a default distribution that runs when you run wsl on a command line:

wslconfig /setdefault Sets the default distribution to .

Example: (using PowerShell)
wslconfig /setdefault Ubuntu would set my default distribution to Ubuntu. Now when I run wsl npm init it will run in Ubuntu. If I run wsl it will open an Ubuntu session.

To unregister and reinstall a distribution:

wslconfig /unregister
Unregisters the distribution from WSL so it can be reinstalled or cleaned up.

For example: wslconfig /unregister Ubuntu would remove Ubuntu from the distributions available in WSL. When I run wslconfig /list it will not be listed.

To reinstall, find the distribution in the Microsoft store and select «Launch».

Configure per distro launch settings with wslconf

Available in Windows Build 17093 and later

Automatically configure functionality in WSL that will be applied every time you launch the subsystem using wsl.conf . This includes automount options and network configuration.

wsl.conf is located in each Linux distribution in /etc/wsl.conf . If the file is not there, you can create it yourself. WSL will detect the existence of the file and will read its contents. If the file is missing or malformed (that is, improper markup formatting), WSL will continue to launch as normal.

Here is a sample wsl.conf file you could add into your distributions:

When launching multiple Linux shells for the same distribution, you must wait until the Linux subsystem stops running, this can take approximately 8 seconds after closing the last instance of the distribution shell. If you launch a distribution (ie. Ubuntu), modify the wsl.conf file, close the distribution, and then re-launch it. You might assume that your changes to the wsl.conf file have immediately gone into effect. This is not currently the case as the subsystem could still be running. You must wait

8 seconds for the subsystem to stop before relaunching in order to give enough time for your changes to be picked up. You can check to see whether your Linux distribution (shell) is still running after closing it by using PowerShell with the command: wsl —list —running . If no distributions are running, you will receive the response: «There are no running distributions.» You can now restart the distribution to see your wsl.conf updates applied.

Configuration Options

In keeping with .ini conventions, keys are declared under a section.

WSL supports four sections: automount , network , interop , and user .

automount

key value default notes
enabled boolean true true causes fixed drives (i.e C:/ or D:/ ) to be automatically mounted with DrvFs under /mnt . false means drives won’t be mounted automatically, but you could still mount them manually or via fstab .
mountFsTab boolean true true sets /etc/fstab to be processed on WSL start. /etc/fstab is a file where you can declare other filesystems, like an SMB share. Thus, you can mount these filesystems automatically in WSL on start up.
root String /mnt/ Sets the directory where fixed drives will be automatically mounted. For example, if you have a directory in WSL at /windir/ and you specify that as the root, you would expect to see your fixed drives mounted at /windir/c
options comma-separated list of values empty string This value is appended to the default DrvFs mount options string. Only DrvFs-specific options can be specified. Options that the mount binary would normally parse into a flag are not supported. If you want to explicitly specify those options, you must include every drive for which you want to do so in /etc/fstab.

By default, WSL sets the uid and gid to the value of the default user (in Ubuntu distro, the default user is created with uid=1000,gid=1000). If the user specifies a gid or uid option explicitly via this key, the associated value will be overwritten. Otherwise, the default value will always be appended.

Note: These options are applied as the mount options for all automatically mounted drives. To change the options for a specific drive only, use /etc/fstab instead.

Mount options

Setting different mount options for Windows drives (DrvFs) can control how file permissions are calculated for Windows files. The following options are available:

Key Description Default
uid The User ID used for the owner of all files The default User ID of your WSL distro (On first installation this defaults to 1000)
gid The Group ID used for the owner of all files The default group ID of your WSL distro (On first installation this defaults to 1000)
umask An octal mask of permissions to exclude for all files and directories 000
fmask An octal mask of permissions to exclude for all files 000
dmask An octal mask of permissions to exclude for all directories 000
metadata Whether metadata is added to Windows files to support Linux system permissions disabled
case Determines directories treated as case sensitive and whether new directories created with WSL will have the flag set. See Per-directory case sensitivity and WSL for a detailed explanation of the options. dir

Note: The permission masks are put through a logical OR operation before being applied to files or directories.

network

Section label: [network]

key value default notes
generateHosts boolean true true sets WSL to generate /etc/hosts . The hosts file contains a static map of hostnames corresponding IP address.
generateResolvConf boolean true true set WSL to generate /etc/resolv.conf . The resolv.conf contains a DNS list that are capable of resolving a given hostname to its IP address.

interop

Section label: [interop]

These options are available in Insider Build 17713 and later.

key value default notes
enabled boolean true Setting this key will determine whether WSL will support launching Windows processes.
appendWindowsPath boolean true Setting this key will determine whether WSL will add Windows path elements to the $PATH environment variable.

Section label: [user]

These options are available in Build 18980 and later.

key value default notes
default string The initial username created on first run Setting this key specifies which user to run as when first starting a WSL session.

Configure global options with .wslconfig

Available in Windows Build 19041 and later

You can configure global WSL options by placing a .wslconfig file into the root directory of your users folder: C:\Users\ \.wslconfig . Many of these files are related to WSL 2, please keep in mind you may need to run wsl —shutdown to shut down the WSL 2 VM and then restart your WSL instance for these changes to take affect.

Here is a sample .wslconfig file:

This file can contain the following options:

WSL 2 Settings

Section label: [wsl2]

These settings affect the VM that powers any WSL 2 distribution.

key value default notes
kernel string The Microsoft built kernel provided inbox An absolute Windows path to a custom Linux kernel.
memory size 50% of total memory on Windows or 8GB, whichever is less; on builds before 20175: 80% of your total memory on Windows How much memory to assign to the WSL 2 VM.
processors number The same number of processors on Windows How many processors to assign to the WSL 2 VM.
localhostForwarding boolean true Boolean specifying if ports bound to wildcard or localhost in the WSL 2 VM should be connectable from the host via localhost:port.
kernelCommandLine string Blank Additional kernel command line arguments.
swap size 25% of memory size on Windows rounded up to the nearest GB How much swap space to add to the WSL 2 VM, 0 for no swap file.
swapFile string %USERPROFILE%\AppData\Local\Temp\swap.vhdx An absolute Windows path to the swap virtual hard disk.
  • Note: This value is true for Windows Build 19041 and may be different in Windows builds in the Insiders program

Entries with the path value must be Windows paths with escaped backslashes, e.g: C:\\Temp\\myCustomKernel

Entries with the size value must be a size followed by a unit, for example 8GB or 512MB .

Читайте также:  Windows 10 процессор celeron
Оцените статью