- Remove From My Forums
-
Question
-
I have installed openssh server from optional features in windows 10 and it works. Initially sshd took a password used by administrative user (me) who installed it. Now I want to change password used for ssh login, but I can not. What I have tried:
I have changed my user password.
I have tried to change password on Log On tab in sshd service properties for NT SERVICE/sshd user.
I have tried to find sshd user in users and groups management to change password there, but could not find it.
Nothing changed. I still login to ssh with old password.
How to change password for openssh server in windows 10?
-
Edited by
Sunday, April 29, 2018 10:46 AM
typo
-
Edited by
Answers
-
Hi,
You can reset the password using passwd command.
For more information, please read this article:
User Accounts and Permissions
https://docs.microsoft.com/en-us/windows/wsl/user-support
For further information, please ask in the following forum:
https://github.com/Microsoft/WSL/issues
The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.
Please remember to mark the replies as answers if they help.
If you have feedback for TechNet Subscriber Support, contact
tnmff@microsoft.com.-
Marked as answer by
foormanek
Monday, April 30, 2018 8:17 AM
-
Marked as answer by
So here’s the situation: I’m new to my job so I still have no idea what they are talking about like this one, my boss tells me to change my password in docs2comply.com by SSH.
I don’t know what the heck he meant by that. But he said that I’ll ask some co workers later but I want to make an impression so I need to figure out this myself. A little help here would be really appreciated.
So if anyone here knows what I mean please guide me through this.
asked Mar 25, 2013 at 15:29
1
If you’re on unix/linux, then login to your ssh server like this:
ssh -l <username> <servername>
this’ll prompt you for password, if you have not yet transferred your ssh keys to the server.
If you’re on Windows, then use putty for doing the same.
Then after logging in, do this:
passwd
this will prompt your for your current password on the server and then new password
answered Mar 25, 2013 at 15:38
6
Follow this article to change SSH password in simple steps.
First of all, enable the SSH with this command:
ssh [email protected]
Login to your server with SSH
Type this command to change the password.
passwd
The terminal will ask for a password.
Press ‘Enter’ after typing a strong password.
- Retype the same password, and press enter.
Your password is set.
What is SSH?
SSH is known as Secure Shell or Secure Socket Shell.
Basically, it is a secure network protocol. SSH helps admins in taking the access to the servers in a secure environment. It sends the command in cryptographic form.
Before the SSH, Telnet was the popular Application Protocol. But it was using the plain text to convey the commands. Overall, it was not a secure protocol.
Therefore, SSH became popular after the release.
The difference between SSH and Telnet is sort of similar to HTTP vs HTTPS.
According to RFC 4252, the Secure Shell Protocol (SSH) is a protocol for secure remote login and other secure network services over an insecure network.
The set of tools makes the communication secure and cryptic.
There are three sets of utilities: slogin, ssh, scp.
Functions of SSH
After enabling the SSH, you can use various fucntions.
Few of them are:
- Providing access to a network system or devices that are SSH enabled.
- Making transferring of files secure and interactive
- File transfer on automation
- Secured commands execution
- Securing the management of network infrastructure components.
SSH is also used in various scripts that enable the access of data.
History of SSH
The first stable version of SSH was appeared in 1995. After Tatu Ylonen designed the original SSH protocol in 1995, he published it as open source.
The first version is already outdated and insecure to use. But with various improvement and updates, SSH is one of the most used application protocol in the industry.
Internet Engineering Task Force (IETF) iadopted the current version of Secure Shell protocols, SSH-2 as a Standards Track specification.
In Conclusion
SSH is a secure application network protocol.
But changing the passwords at fix interval of time is a good idea.
In this article, I told you how to change the SSH password.
I hope you can change SSH password now.
If any doubts, leave the comments below.
SSH-server based on the OpenSSH package is part of the operating system in all modern versions of Windows. In this article, we’ll show you how to install and configure the OpenSSH server on Windows 10/11 and Windows Server 2022/2019 and connect to it remotely via a secure SSH connection (just like in Linux 🙂).
Contents:
- How to Install OpenSSH Server on Windows?
- Configuring SSH Server on Windows
- Sshd_config: OpenSSH Server Configuration File
- How to Connect to a Remote Windows Computer via SSH?
- Checking SSH Connection Logs in Windows
How to Install OpenSSH Server on Windows?
The OpenSSH Server package is a part of all modern versions of Windows 10 (starting with 1803), Windows 11, and Windows Server 2022/2019 as a Feature on Demand (FoD). To install the OpenSSH server, open the elevated PowerShell prompt and run the command:
Get-WindowsCapability -Online | Where-Object Name -like ‘OpenSSH.Server*’ | Add-WindowsCapability –Online
Or using DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
If your computer is directly connected to the Internet, the OpenSSH.Server package will be downloaded and installed on Windows.
You can also install OpenSSH on Windows 10/11 through the modern Settings panel (Settings -> Apps and features -> Optional features -> Add a feature). Find Open SSH Server in the list and click Install.
On computers in disconnected (offline) environments, you can install the OpenSSH Server from the Feature on Demand ISO image (available in your account on the Microsoft websites: MSDN or my.visualstudio.com). Download the ISO and extract its contents to the E:FOD folder (you can only extract the file OpenSSH-Server-Package~31bf3856ad364e35~amd64~~.cab
) and install the Windows feature from the local repository:
Add-WindowsCapability -Name OpenSSH.Server~~~~0.0.1.0 -Online -Source E:FOD
An MSI installer for OpenSSH for Windows is also available in the official Microsoft repository on GitHub (https://github.com/PowerShell/Win32-OpenSSH/releases/). For example, for Windows 10 x64, you need to download and install the OpenSSH-Win64-v8.9.1.0.msi package. The following PowerShell command will download the MSI file and install the OpenSSH client and server on your computer:
Invoke-WebRequest https://github.com/PowerShell/Win32-OpenSSH/releases/download/v8.9.1.0p1-Beta/OpenSSH-Win64-v8.9.1.0.msi -OutFile $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi
You can install an OpenSSH server in previous Windows versions as well (Windows 8.1, Windows Server 2016/2012R2/2012). Check the example on how to install and configure Win32-OpenSSH in the article “How to Configure SFTP Server (SSH FTP) on Windows?”.
To make sure the OpenSSH server has been installed, run the command:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Ser*'
State : Installed
Configuring SSH Server on Windows
After installing the OpenSSH server on Windows, two services are added:
- ssh-agent (OpenSSH Authentication Agent) – can be used to manage private keys if you have configured SSH key authentication;
- sshd (OpenSSH SSH Server).
You need to change the startup type of the sshd service to automatic and start the service using PowerShell:
Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd
Use the netstat command to make sure that the SSH server is running and waiting for the connections on TCP port 22:
netstat -na| find ":22"
Make sure that Windows Defender Firewall allows inbound connections to Windows through TCP port 22:
Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled
Name DisplayName Description Enabled ---- ----------- ----------- ------- OpenSSH-Server-In-TCP OpenSSH SSH Server (sshd) Inbound rule for OpenSSH SSH Server (sshd) True
If the rule is disabled (Enabled=False) or missing, you can create a new inbound rule using the New-NetFirewallRule cmdlet:
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
By default, key OpenSSH components are located in these folders:
- OpenSSH Server executables:
C:WindowsSystem32OpenSSH
(sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe, etc.) - The sshd_config file (created after the first service start of the service):
C:ProgramDatassh
- The authorized_keys file and keys can be stored in the user profile folder:
%USERPROFILE%.ssh
Sshd_config: OpenSSH Server Configuration File
You can change your OpenSSH server settings in the config file: %programdata%sshsshd_config
. This is a plain text file with a set of directives. You can use any text editor for editing:
start-process notepad C:Programdatasshsshd_config
For example, to deny SSH connection for a specific domain user account (or all users in the specified domain), add these directives to the end of the file:
DenyUsers woshubadmin@192.168.1.10 DenyUsers corp*
To allow SSH connection to the specific domain security group only:
AllowGroups woshubsshadmins
You can allow access to a local user group:
AllowGroups sshadmins
By default, all Windows users can connect to OpenSSH. Directives in the sshd_config files are processed in the following order: DenyUsers, AllowUsers, DenyGroups, AllowGroups.
You can deny SSH login for the accounts with administrator privileges. In this case, if you need to perform any privileged actions in your SSH session, you will have to use runas.
DenyGroups Administrators
The following directives allow you to access Windows using SSH private keys or a password.
PubkeyAuthentication yes PasswordAuthentication yes
You can change the default TCP/22 port on which OpenSSH Server connections are accepted in the sshd_config configuration file using the Port directive.
After making any changes to the sshd_config file, you need to restart the sshd service
restart-service sshd
How to Connect to a Remote Windows Computer via SSH?
Now you can try to connect to your Windows 10 computer using the SSH client (I’m using putty in this example).
You can use the built-in Windows SSH client to connect to a remote host. To do this, open the command prompt and run the following command:
ssh max@192.168.13.12
In this example, max is the username on the remote Windows computer, and 192.168.13.12 is the IP address or DNS name of the computer.
Note that you can use the following username formats when connecting to Windows via SSH:
max@server1
– local Windows usermax@woshub.com@server1
– Active Directory user or Microsoft/Azure account (use the UserPrincipalName format)woshubmax@server1
– NetBIOS name format
In an Active Directory domain, you can use Kerberos authentication in SSH. To do this, you need to enable the following directive in sshd_config:
GSSAPIAuthentication yes
You can now transparently connect to an SSH server from a domain-joined Windows machine with a domain user session. In this case, the user’s password will not be requested, and SSO authentication via Kerberos will be performed:
ssh -K server1
The first time you connect, you will be prompted to add the host to the list of known SSH hosts (C:Usersyour_user.sshknown_hosts
).
Click Yes
, and login under your Windows user account.
If the SSH connection is successful, you will see the cmd.exe shell prompt.
admin@win10pc C:Usersadmin>
You can run different commands, scripts, and apps in the SSH command prompt.
I prefer working in the PowerShell console. To start it, run:
powershell.exe
In order to change the default cmd.exe shell in OpenSSH to PowerShell, make changes to the registry using the following PowerShell command:
New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String –Force
Restart your SSH connection and make sure that PowerShell is now used as a default SSH shell (this is indicated by the prompt PS C:Usersadmin>
).
The PowerShell prompt has been started in my SSH session, where the usual functions work: tab autocomplete, PSReadLine syntax highlighting, command history, etc. If the current user is a member of the local administrators’ group, all session commands are executed elevated even if UAC is enabled.
OpenSSH server on Windows can be used in various SSH tunneling scenarios.
Checking SSH Connection Logs in Windows
By default in Windows SSH server connection logs are written not to text files, but to a separate event log via Event Tracing for Windows (ETW). Open the Event Viewer console (eventvwr.msc
) and navigate to Application and services logs -> OpenSSH -> Operational.
If you successfully connect to the SSH server using a password, an event will appear in the log:
EventID: 4 sshd: Accepted password for root from 192.168.1.53 port 65749 ssh2
If SSH key authentication was performed, you will see the following event:
sshd: Accepted publickey for locadm from 192.168.1.53 port 61426 ssh2: ED25519 SHA256:FEHDEC/G42FS23209C2KMb4335923pigN31s3qMK322lGibD
If you want the SSH connection logs to be written to a local text file, you need to enable the following parameters in the sshd_config file:
SyslogFacility LOCAL0 LogLevel INFO
Restart the sshd service and make sure that the SSH server logs are now written to a plain text file C:ProgramDatasshlogssshd.log
In previous article i describe How to install Open SSH in Windows 10 as Optional Feature and use it. Today i will continue with OpenSSH and i will describe step by step how can install OpenSSH Server in Windows 10 and configure it.
OpenSSH Server and client included in Windows 10 v.1809 and later and in Windows Server 2019
So let’s start!!
How to Identify if Windows 10 Open SSH Server installed from GUI
Before start with the installation its better to identify if already OpenSSH Server installed.
- Click Start and Gear Icon
- Click in Apps
- From the right side select Manage Optional Features.
- if you see Open SSH Server then it means that already installed.
- If you can’t see this means that you must install the Feature.
How to Identify if OpenSSH Server installed from Powershell
If you like Powershell you can use the following command to identify if OpenSSH Server already installed
Get-WindowsCapability -Online | ? name -like "openssh*"
Check the State status to identify if is installed or not
- State:Installed means it’s already installed
- State:Not Present means it’s not installed
How to Install in Windows 10 the OpenSSH Server from GUI
After identify that OpenSSH Server it’s not installed we can proceed to install the OpenSSH Server
- Click Start and Gear Icon
- Click in Apps
- From the right side select Manage Optional Features
- Click Add Feature
- Find and click Open SSH Server
- Click Install
How to Install in Windows 10 the OpenSSH Server from Powershell
If you would like to proceed the installation of OpenSSH Server from Powershell you can do it with one command.
Type the following command and wait to finish the installation
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
How to start and Configure in Windows 10 the OpenSSH Server
Now it’s time to Configure OpenSSH Server to start use it.
- Open Powershell command as Administrator
- Type the following command to start the Service of the OpenSSH Server
Start-service sshd
- Type the following command to add Automatic Startup in Service
Set-Service -Name sshd -StartupType 'Automatic'
- Type the following command to find the Rule for OpenSSH Server in Windows Firewall and verify that is Allow
Get-NetFirewallRule -Name *ssh*
How to connect with ssh from Linux to Windows 10 OpenSSHServer
The reality with ssh is that most of them use it with Public key authentication instead of password authentication because it prevent attacks.
But by default after the installation the OpenSSH Server use password authentication.
We will keep the password authentication to be able to connect through the configuration that must be done to use the Public key authentication
So for the best practices and better security let’s explain how can generate ssh keys and use it to connect in OpenSSH Server
- Login in Windows 10 OpenSSH Server and create the users that you want to connect.
- If you have Domain users and have already decide which should be connect then avoid the previous step
- Login in the Linux that you will use it to connect in OpenSSH Server
- Type the following command to start generate the keys
- ssh keygen
- It will ask how you would like to save the file name but you can leave it as the default and click Enter
- Also it will ask to create a passphrase.
- Just write down a passphrase and keep it in a safe place because it will ask when you will connect in OpenSSH Server.
- Now if you type ls to see the files and folder of the ssh directory you will see 2 files. These are the private key and the public key with the extension .pub
- id_rsa
- id_rsa.pub
- To be able create the authentication must be copy the public key in the Openssh Server in the following path of the user which will connect from Linux. Note that we must have create the user before proceed with this step.
- The name of the public key file must be authorized_keys in the .ssh folder
- C:Users<username>.ssh
- So let’s type the following command from the Linux which create the ssh keys and replace the user1@192.168.50.151 with your username and ip address of the opensshserver
- scp ~/.ssh/id_rsa.pub user1@192.168.50.151:»c:usersuser1.sshauthorized_keys»
- Login in the Openssh server and verify that the authorized_keys created in the .ssh of the user folder.
- Now we must configure the permission of the authorized_keys because if you try to connect as it you will get an error Permission denied (publickey,keyboard-interactive)
- If we check the permissions of the authorized_keys file we will see that has access the user which will connect in my scenario is the user1 and the Domain Administrator.
- But these users must be removed.
- If you search in Google you will find most of the Blogs and forums to say that you can download the Powershell module OpenSSHUtil but this module has been deprecated and if you try you will fail to downloaded
- Before try to remove the access from users in the authorized_keys file must be disable the inheritance. If you don’t do it and try to remove the users with icacls command then you will get the info that succesfull proceed with the file but if you will check the permission will be the same without remove the users.
- Right click in authorized_keys file — Properties.
- Click Advanced button.
- Click Disable inheritance.
- Click Convert inherited permissions into explicit permissions on this object.
- Login again in Linux which will use it to connect and type the following command to connect with ssh and password authentication for now
- ssh user1@192.168.50.151
- After connect type the following commands to remove the user access from the authorized_keys
- Icacls «authorized_keys» /remove user1
- Icacls «authorized_keys» /remove administrator
- Now type the following command to check the permissions in the file.
- Only these users must has access in this file
- icacls authorized_keys
- The last step is to disable the password authentication and enable the Pubkey authentication from the ssh_config file to be able authorized only with the ssh keys and not with password
How to disable password authentication in OpensshServer
After the basic configuration of OpensshServer to set Automatic the Service and verify the Rule in Windows Firewall you can proceed in more advance configuration.
Let’s explain how can change configuration of Openssh server.
- Open Powershell as Administrator
- Type the command notepad.exe $env:PROGRAMDATAsshsshd_config to open the ssh_config file
- Change the following lines with these values.
-
- PubkeyAuthentication yes
- PasswordAuthentication no
PermitEmptyPasswords no
- Then type the following commands to restart the Openssh Server service
- Stop-Service sshd
- Start-Service sshd
- Let’s connect in Linux and type the command to connect trough ssh.
- If all works without issues you will see that ask the passphrase before connect
- Type it and the connection will be established.
If you failed to connect with Public key authentication then the better solution is to use Logs of SSH to identify the cause of the issue.
This has been change from previous versions and now the SSH Logs located in Windows Event Logs in stead of the C:ProgramDatasshlogssshd.log and you can find it in Application and Services Logs — OpenSSH Logs
I hope my article to help you or explore something new or resolve a problem.
Have a nice weekend !!
I invite you to follow me on Twitter or Facebook. If you have any questions, send me an email at info@askme4tech.com
В современных версиях Windows уже есть встроенный SSH сервер на базе пакета OpenSSH. В этой статье мы покажем, как установить и настроить OpenSSH сервер в Windows 10/11 и Windows Server 2022/2019 и подключиться к нему удаленно по защищенному SSH протоколу (как к Linux).
Содержание:
- Установка сервера OpenSSH в Windows
- Настройка SSH сервера в Windows
- Sshd_config: Конфигурационный файл сервера OpenSSH
- Подключение по SSH к Windows компьютеру
- Логи SSH подключений в Windows
Установка сервера OpenSSH в Windows
Пакет OpenSSH Server включен в современные версии Windows 10 (начиная с 1803), Windows 11 и Windows Server 2022/2019 в виде Feature on Demand (FoD). Для установки сервера OpenSSH достаточно выполнить PowerShell команду:
Get-WindowsCapability -Online | Where-Object Name -like ‘OpenSSH.Server*’ | Add-WindowsCapability –Online
Или при помощи команды DISM:
dism /Online /Add-Capability /CapabilityName:OpenSSH.Server~~~~0.0.1.0
Если ваш компьютер подключен к интернету, пакет OpenSSH.Server будет скачан и установлен в Windows.
Также вы можете установить сервер OpenSSH в Windows через современную панель Параметры (Settings -> Apps and features -> Optional features -> Add a feature, Приложения -> Управление дополнительными компонентами -> Добавить компонент. Найдите в списке OpenSSH Server и нажмите кнопку Install).
На изолированных от интернета компьютерах вы можете установить компонент с ISO образа Features On Demand (доступен в личном кабинете на сайте Microsoft: MSDN или my.visualstudio.com). Скачайте диск, извлеките его содержимое в папку c:FOD (достаточно распаковать извлечь файл
OpenSSH-Server-Package~31bf3856ad364e35~amd64~~.cab
), выполните установку из локального репозитория:
Add-WindowsCapability -Name OpenSSH.Server~~~~0.0.1.0 -Online -Source c:FOD
Также доступен MSI установщик OpenSSH для Windows в официальном репозитории Microsoft на GitHub (https://github.com/PowerShell/Win32-OpenSSH/releases/). Например, для Windows 10 x64 нужно скачать и установить пакет OpenSSH-Win64-v8.9.1.0.msi. Следующая PowerShell команда скачает MSI файл и установит клиент и сервер OpenSSH:
Invoke-WebRequest https://github.com/PowerShell/Win32-OpenSSH/releases/download/v8.9.1.0p1-Beta/OpenSSH-Win64-v8.9.1.0.msi -OutFile $HOMEDownloadsOpenSSH-Win64-v8.9.1.0.msi -UseBasicParsing
msiexec /i c:usersrootdownloadsOpenSSH-Win64-v8.9.1.0.msi
Также вы можете вручную установить OpenSSH сервер в предыдущих версиях Windows (Windows 8.1, Windows Server 2016/2012R2). Пример установки Win32-OpenSSH есть в статье “Настройка SFTP сервера (SSH FTP) в Windows”.
Чтобы проверить, что OpenSSH сервер установлен, выполните:
Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Ser*'
State : Installed
Настройка SSH сервера в Windows
После установки сервера OpenSSH в Windows добавляются две службы:
- ssh-agent (OpenSSH Authentication Agent) – можно использовать для управления закрытыми ключами если вы настроили SSH аутентификацию по ключам;
- sshd (OpenSSH SSH Server) – собственно сам SSH сервер.
Вам нужно изменить тип запуска службы sshd на автоматический и запустить службу с помощью PowerShell:
Set-Service -Name sshd -StartupType 'Automatic'
Start-Service sshd
С помощью nestat убедитесь, что теперь в системе запущен SSH сервер и ждет подключений на порту TCP:22 :
netstat -na| find ":22"
Проверьте, что включено правило брандмауэра (Windows Defender Firewall), разрешающее входящие подключения к Windows по порту TCP/22.
Get-NetFirewallRule -Name *OpenSSH-Server* |select Name, DisplayName, Description, Enabled
Name DisplayName Description Enabled ---- ----------- ----------- ------- OpenSSH-Server-In-TCP OpenSSH SSH Server (sshd) Inbound rule for OpenSSH SSH Server (sshd) True
Если правило отключено (состоянии Enabled=False) или отсутствует, вы можете создать новое входящее правило командой New-NetFirewallRule:
New-NetFirewallRule -Name sshd -DisplayName 'OpenSSH Server (sshd)' -Enabled True -Direction Inbound -Protocol TCP -Action Allow -LocalPort 22
Рассмотрим, где храниться основные компоненты OpenSSH:
- Исполняемые файлы OpenSSH Server находятся в каталоге
C:WindowsSystem32OpenSSH
(sshd.exe, ssh.exe, ssh-keygen.exe, sftp.exe и т.д.) - Конфигурационный файл sshd_config (создается после первого запуска службы):
C:ProgramDatassh
- Файлы authorized_keys и ssh ключи можно хранить в профиле пользователей:
%USERPROFILE%.ssh
Sshd_config: Конфигурационный файл сервера OpenSSH
Настройки сервере OpenSSH хранятся в конфигурационном файле %programdata%sshsshd_config. Это обычный текстовый файл с набором директив. Для редактирования можно использовать любой текстовый редактор (я предпочитаю notepad++). Можно открыть с помощью обычного блокнота:
start-process notepad C:Programdatasshsshd_config
Например, чтобы запретить SSH подключение для определенного доменного пользователя (и всех пользователей указанного домена), добавьте в конце файле директивы:
DenyUsers winitpro[email protected] DenyUsers corp*
Чтобы разрешить подключение только для определенной доменной группы:
AllowGroups winitprosshadmins
Либо можете разрешить доступ для локальной группы:
AllowGroups sshadmins
По умолчанию могут к openssh могут подключаться все пользователи Windows. Директивы обрабатываются в следующем порядке: DenyUsers, AllowUsers, DenyGroups,AllowGroups.
Можно запретить вход под учетными записями с правами администратора, в этом случае для выполнения привилегированных действий в SSH сессии нужно делать runas.
DenyGroups Administrators
Следующие директивы разрешают SSH доступ по ключам (SSH аутентификации в Windows с помощью ключей описана в отдельной статье) и по паролю:
PubkeyAuthentication yes PasswordAuthentication yes
Вы можете изменить стандартный SSH порт TCP/22, на котором принимает подключения OpenSSH в конфигурационном файле sshd_config в директиве Port.
После любых изменений в конфигурационном файле sshd_config нужно перезапускать службу sshd:
restart-service sshd
Подключение по SSH к Windows компьютеру
Теперь вы можете попробовать подключиться к своей Windows 10 через SSH клиент (в этом примере я использую putty).
Вы можете использовать встроенный SSH клиентом Windows для подключения к удаленному хосту. Для этого нужно в командной строке выполнить команду:
ssh [email protected]
В этом примере
alexbel
– имя пользователя на удаленном Windows компьютере, и 192.168.31.102 – IP адрес или DNS имя компьютера.
Обратите внимание что можно использовать следующие форматы имен пользователей Windows при подключении через SSH:
-
[email protected]
– локальный пользователь Windows -
[email protected]@server1
–пользователь Active Directory (в виде UPN) или аккаунт Microsoft/ Azure(Microsoft 365) -
winitpro[email protected]
– NetBIOS формат имени
В домене Active Directory можно использовать Kerberos аутентификацию в SSH. Для этого в sshd_config нужно включить параметр:
GSSAPIAuthentication yes
После этого можно прозрачно подключать к SSH сервер с Windows компьютера в домене из сессии доменного подключается. В этом случае пароль пользователя не указывается и выполняется SSO аутентификация через Kerberos:
ssh -K server1
При первом подключении появится стандартный запрос на добавление узла в список известных SSH хостов.
Нажимаем Да, и в открывшееся окне авторизуемся под пользователем Windows.
При успешном подключении запускается командная оболочка cmd.exe со строкой-приглашением.
[email protected] C:Usersadmin>
В командной строке вы можете выполнять различные команды, запускать скрипты и программы.
Я предпочитаю работать в командной строке PowerShell. Чтобы запустить интерпретатор PowerShell, выполните:
powershell.exe
Чтобы изменить командную оболочку (Shell) по умолчанию в OpenSSH с cmd.exe на PowerShell, внесите изменение в реестр такой командой:
New-ItemProperty -Path "HKLM:SOFTWAREOpenSSH" -Name DefaultShell -Value "C:WindowsSystem32WindowsPowerShellv1.0powershell.exe" -PropertyType String –Force
Осталось перезапустить SSH подключение и убедиться, что при подключении используется командный интерпретатор PowerShell (об этом свидетельствует приглашение
PS C:Usersadmin>
).
В SSH сессии запустилась командная строка PowerShell, в которой работают привычные функции: авто дополнение, раскраска модулем PSReadLine, история команд и т.д. Если текущий пользователь входит в группу локальных администраторов, то все команды в его сессии выполняются с повышенными правами даже при включенном UAC.
Логи SSH подключений в Windows
В Windows логи подключений к SSH серверу по-умолчанию пишутся не в текстовые файлы, а в отдельный журнал событий через Event Tracing for Windows (ETW). Откройте консоль Event Viewer (
eventvwr.msc
>) и перейдите в раздел Application and services logs -> OpenSSH -> Operational.
При успешном подключении с помощью к SSH серверу с помощью пароля в журнале появится событие:
EventID: 4 sshd: Accepted password for root from 192.168.31.53 port 65479 ssh2
Если была выполнена аутентификация с помощью SSH ключа, событие будет выглядеть так:
sshd: Accepted publickey for locadm from 192.168.31.53 port 55772 ssh2: ED25519 SHA256:FEHDEC/J72Fb2zC2oJNb45678967kghH43h3bBl31ldPs
Если вы хотите, чтобы логи писались в локальный текстовый файл, нужно в файле sshd_config включить параметры:
SyslogFacility LOCAL0 LogLevel INFO
Перезапустите службу sshd и провеьте, что теперь логи SSH сервера пишутся в файл C:ProgramDatasshlogssshd.log
Windows 10 recently added OpenSSH as an optional Windows feature. I’ve found the config file C:WindowsSystem32OpenSSHsshd_config and gave myself rights to modify it.
Here’s the file I have:
# $OpenBSD: sshd_config,v 1.84 2011/05/23 03:30:07 djm Exp $
# This is the sshd server system-wide configuration file. See
# sshd_config(5) for more information.
# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin
# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented. Uncommented options override the
# default value.
#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::
# The default requires explicit activation of protocol 1
#Protocol 2
# HostKey for protocol version 1
#HostKey /etc/ssh/ssh_host_key
# HostKeys for protocol version 2
#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_dsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
# Lifetime and size of ephemeral version 1 server key
#KeyRegenerationInterval 1h
#ServerKeyBits 1024
# Logging
# obsoletes QuietMode and FascistLogging
#SyslogFacility AUTH
#LogLevel INFO
# Authentication:
#LoginGraceTime 2m
#PermitRootLogin yes
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10
#RSAAuthentication yes
#PubkeyAuthentication yes
# The default is to check both .ssh/authorized_keys and .ssh/authorized_keys2
# but this is overridden so installations will only check .ssh/authorized_keys
AuthorizedKeysFile .ssh/authorized_keys
# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#RhostsRSAAuthentication no
# similar for protocol version 2
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# RhostsRSAAuthentication and HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes
# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no
# Change to no to disable s/key passwords
ChallengeResponseAuthentication no
# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no
# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication. Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM no
#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
#X11Forwarding no
#X11DisplayOffset 10
#X11UseLocalhost yes
#PrintMotd yes
#PrintLastLog yes
#TCPKeepAlive yes
#UseLogin no
#UsePrivilegeSeparation yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS yes
#PidFile /var/run/sshd.pid
#MaxStartups 10
#PermitTunnel no
#ChrootDirectory none
# no default banner path
#Banner none
# override default of no subsystems
Subsystem sftp sftp-server.exe
# Example of overriding settings on a per-user basis
#Match User anoncvs
# X11Forwarding no
# AllowTcpForwarding no
# ForceCommand cvs server
# PubkeyAcceptedKeyTypes ssh-ed25519*
ChallengeResponseAuthentication no
PasswordAuthentication no
UsePAM no
The only non-default entries are the bottom 3 lines that should disable password authentication. After I change the file I go to services and restart ssh-agent
, SSH Server Broke
, and SSH Server Proxy
in hopes they’ll see the changes in the config file. I then use putty to ssh to localhost. Putty asks for my username but then it asks for my password and successfully connects when I put it in.
In Windows 10’s new SSH feature how can I disable password authentication?
asked Dec 15, 2017 at 18:06
Corey OgburnCorey Ogburn
2911 gold badge3 silver badges12 bronze badges
2
In Windows 10 v1803 (aka 17134.191) it has changed.
Edit c:ProgramDatasshsshd_config (aka %PROGRAMDATA%sshsshd_config)
answered Aug 6, 2018 at 1:48
You note that you have the service «SSH Server Proxy» — this service is not part the «OpenSSH Server (Beta)» optional feature in Windows 10 Fall Creators Update (v1709). It is part of Windows Developer mode — I wonder if this (possibly in combination with WSL) is leading to you connecting to a different OpenSSH server unintentionally, and why it appears the config is not being respected.
Try stopping or disabling the «SSH Server Proxy» service and see if the behavior changes, or alternatively, adjust the port # in your WindowsSystem32OpenSSHsshd_config to a non-standard port and test again.
I just deployed a lab Windows 10 v1709 VM to test this, and can confirm that by uncommenting the «# PasswordAuthentication yes» line (and switching the value to «no») that with only an sshd service restart, it blocks password-based logins.
The only services «OpenSSH Server (beta)» gives me are «sshd» and «ssh-agent». Fresh VM, without Windows Developer Mode or WSL / Bash on Ubuntu enabled.
answered Dec 29, 2017 at 19:52
Joshua McKinnonJoshua McKinnon
1,4211 gold badge14 silver badges26 bronze badges
1