Ubuntu cursor for windows 10

1. Overview

SSH, the secure shell, is often used to access remote Linux systems. But its authentication mechanism, where a private local key is paired with a public remote key, is used to secure all kinds of online services, from GitHub and Launchpad to Linux running on Microsoft’s Azure cloud.

Generating these keys from Linux is easy, and thanks to Ubuntu on WSL, you can follow the same process from Windows 10. But even without Ubuntu, SSH keys can also be generated with the free and open source OpenSSH client built into Windows 10 or with PuTTY for Windows 8.1 and earlier.

Over the following few steps, we’ll guide you through the process of generating SSH keys using Ubuntu on WSL, OpenSSH, and PuTTY.

Requirements

All you need is a PC running Windows and one of the following installed:

  • Ubuntu on WSL for Windows 10
  • The OpenSSH client built into Windows 10
  • The puttygen.exe executable from PuTTY for Windows 7 or 8.1

If you don’t already have Ubuntu on WSL, take a look at our Install Ubuntu on WSL tutorial.

screenshot

Originally authored by Graham Morrison.


2. Passphrase considerations

When creating the SSH key pair, as shown in the following steps, you can choose to either lock your private key with a passphrase or use no passphrase at all.

Adding a passphrase requires the same passphrase to be entered whenever the key pair is used. Not adding a passphrase removes this requirement. For this reason, creating a key pair without a passphrase is more convenient and potentially essential for certain scripts and automation tasks. But it’s also less secure.

If a third-party gains access to a private key without a passphrase they will be able to access all connections and services using the public key.

A good compromise between convenience and security is to generate a separate key pair for each service or connection you want to use, adding a passphrase only for critical services. If you suspect a key has been compromised, simply generate a new pair for that service and remove the less secure key.


3. Key generation with Ubuntu on WSL

Launch Ubuntu on WSL from the start menu and make sure SSH is installed by entering following command at the command prompt:

sudo apt install openssh-client

The key generation process is identical to the process on a native Linux or Ubuntu installation. With SSH installed, run the SSH key generator by typing the following:

ssh-keygen -t rsa

77777777

You will be asked two questions. The first asks where to save the key, and you can press return to accept the default value. The second question asks for the passphrase. As discussed, entering a passphrase will require you to use the same passphrase whenever the key is accessed.

However, the passphrase isn’t a requirement, and pressing return (twice) will generate a key pair without one. Consequently, you won’t be asked for a passphrase when using your key.

When the process has finished, the private key and the public key can be found in the ~/.ssh directory accessible from the Ubuntu terminal, or the following folder from Windows file manager:

\\wsl$\\Ubuntu\home\<username>\.ssh\

888888


4. Key generation with OpenSSH

Recent versions of Windows 10 include the OpenSSH client by default, but if yours does not or you’re unsure, follow these steps:

Open Settings and then navigate to Apps > Apps and Features > Optional Features:

image7

image6

Scan this list to see if OpenSSH client is already installed. If not, at the top of the page select Add a feature, then, to install the OpenSSH client, locate OpenSSH Client and click Install

Once the installation completes, return to Apps > Apps and Features > Optional Features and you should see the OpenSSH component(s) listed:

image10

You can optionally install the OpenSSH client using PowerShell, first launch ‘Windows PowerShell’ as an Administrator. To check the status of the OpenSSH client type the command:

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

This should return:

Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed

image8

If OpenSSH client is listed as “NotPresent” you can install by typing:

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

The command should return:

Path          :
Online        : True
RestartNeeded : False

image5

Finally, to generate your keys, launch ‘Windows PowerShell’ as an Administrator, and type:

ssh-keygen

55555


5. Key generation with Putty

To generate a key pair with the PuTTY key generator, simply run puttygen.exe and click the Generate button in the window that appears.

You will be asked to move the mouse and press keys to improve the random number generation at the heart of SSH security. After this, the raw contents of the public key will be displayed alongside its fingerprint and a timestamp comment.

Two important fields, Key passphrase and Confirm passphrase, allow you to enter a passphrase to protect the private key.

Finally, you will need to export both the private and public keys separately:

  • to export the private key, select Export OpenSSH key from the Conversions menu
  • to export the public key, click Save public key from the main window

Public keys typically use the .pub suffix. By convention, the private key is usually called id_rsa and the public key id_rsa.pub, but this isn’t a requirement. It’s common to have many keys with more descriptive filenames, for instance.

screenshot


6. Getting help

Congratulations! You have just generated a SSH key pair from Windows 10. You can now add the public key to those services you wish to authenticate.

If you need more details on using SSH keys, take a look at the Ubuntu community documentation, and if you get stuck, help is always at hand:

  • Ask Ubuntu
  • Ubuntu Forums
  • IRC-based support

Was this tutorial useful?

Thank you for your feedback.


SSH, the secure shell, is often used to access remote Linux systems. But its authentication mechanism, where a private local key is paired with a public remote key, is used to secure all kinds of online services, from GitHub and Launchpad to Linux running on Microsoft’s Azure cloud. By following this post you will be able to generate SSH keys on Windows 10 using Ubuntu on Windows and PuTTy. Generating these keys from Linux is easy, and thanks to Ubuntu on Windows, you can follow the same process from Windows 10. But even without Ubuntu, SSH keys can also be generated with the free and open source Windows application, PuTTy 

Over the following few steps, we’ll guide you through the process of generating SSH keys using both Ubuntu on Windows and PuTTY.

How to Generate SSH Keys on Windows 10 with Ubuntu

Requirements to Generate SSH Keys on Windows 10

All you need is a PC running Windows 10 and either of the following installed:

  • Ubuntu on Windows
  • The puttygen.exe executable from PuTTY

Passphrase considerations

When creating the SSH key pair, as shown in the following steps, you can choose to either lock your private key with a passphrase or use no passphrase at all.

Adding a passphrase requires the same passphrase to be entered whenever the key pair is used. Not adding a passphrase removes this requirement. For this reason, creating a key pair without a passphrase is more convenient and potentially essential for certain scripts and automation tasks. But it’s also less secure.

If a third party gains access to a private key without a passphrase they will be able to access all connections and services using the public key.

A good compromise between convenience and security is to generate a separate key pair for each service or connection you want to use, adding a passphrase only for critical services. If you suspect a key has been compromised, simply generate a new pair for that service and remove the less secure key.

Launch Bash on Ubuntu on Windows from the start menu and make sure SSH is installed by entering following command at the command prompt:

sudo apt install ssh

The key generation process is identical to the process on a native Linux or Ubuntu installation. With SSH installed, run the SSH key generator by typing the following:

ssh-keygen -t rsa

You will be asked two questions. The first ask where to save the key, and you can press return to accept the default value. The second question asks for the passphrase. As discussed, entering a passphrase will require you to use the same passphrase whenever the key is accessed.

However, the passphrase isn’t a requirement, and pressing return (twice) will generate a key pair without one. Consequently, you won’t be asked for a passphrase when using your key.

When the process has finished, the private key and the public key can be found in the ~/.ssh directory accessible from the Ubuntu terminal, or the following folder from Windows file manager:

C:\Users\<Windows username>\AppData\Local\lxss\home\<Ubuntu username>\.ssh

Both the AppData and lxss directories are hidden from the default view and will need to be entered manually.

Generate SSH Keys on Windows 10 with PuTTY

To generate a key pair with the PuTTY key generator, simply run andputtygen.exe click the Generate button in the window that appears.

You will be asked to move the mouse and press keys to improve the random number generation at the heart of SSH security. After this, the raw contents of the public key will be displayed alongside its fingerprint and a timestamp comment.

Two important fields, Key passphrase and Confirm passphrase, allow you to enter a passphrase to protect the private key.

Finally, you will need to export both the private and public keys separately:

  • to export the private key, select Export OpenSSH key from the Conversions menu
  • to export the public key, click Save public key from the main window

Public keys typically use the suffix.pub. By convention, the private key is usually called andid_rsa the public key,id_rsa.pub but this isn’t a requirement. It’s common to have many keys with more descriptive filenames, for instance.

Searching help for generating SSH keys on Windows 10

Congratulations! You have just generated an SSH key pair from Windows 10. You can now add the public key to those services you wish to authenticate.

Also Read- Most Useful SSH Command And SCP Command With Examples

That’s all, In this article, we have explained How to Generate SSH Keys on Windows 10 with Ubuntu. I hope you enjoy this article. If you like this article, then just share it. If you have any questions about this article, please comment.

Home » KB » Security » How to Generate SSH Key in Windows 10 or 11

Secure Shell (SSH) is a method for establishing a secure connection between two computers. Key-based authentication uses a key pair, with the private key on a remote server and the corresponding public key on a local machine. When the keys match, access is granted to the remote user.

This guide will show you how to generate an SSH key pair in Windows.

Tutorial on how to generate SSH keys in Windows.

Prerequisites

  • A system running Windows 10 or Windows 11.
  • A user account with administrative privileges.
  • Access to the command prompt.
  • A web browser to download PuTTY.

Generate SSH Key Pair in Windows via OpenSSH (ssh-keygen)

ssh-keygen is a command-line tool that is used to generate, manage, and convert SSH authentication keys. As of Windows 10, the OpenSSH client is included by default, which means you can use it directly from the Command Prompt or PowerShell.

Follow the steps below to use ssh-keygen for generating a key pair.

Step 1: Verify if OpenSSH Client is Installed

Start by checking to see if you have the OpenSSH client installed:

1. Open Settings and click System in the left panel.

2. Scroll down and click the Optional features heading.

Open the optional features setting in Windows.

3. Scroll down the list to see if OpenSSH Client is listed. If it is there, then OpenSSH has already been installed on your system, and you can move on to the next section.

If OpenSSH Client is not in the Added features list, click the View features button at the top to install OpenSSH Client.

View optional features in Windows.

4. Type OpenSSH in the search bar and check the box next to OpenSSH Client. Then, click Next to install the feature.

Add the OpenSSH Client feature in Windows.

5. In the next window, click the Add button to confirm that you want to install OpenSSH Client.

Install OpenSSH Client.

Wait for the installation to complete, and you can move on to the next section.

Step 2: Use OpenSSH to Generate an SSH Key Pair

Follow the steps below to generate an SSH key pair via OpenSSH:

1. Press the Windows key and type cmd. Press Enter to open the Command Prompt.

2. In the command prompt, run the following command:

ssh-keygen

3. You can use the default name for the keys, or you can choose more descriptive names to help you distinguish between keys if you are using multiple key pairs. To stick to the default option, press Enter.

Note: If a file with the same name already exists, you will be asked whether you want to overwrite the file.

4. When prompted, enter a passphrase or hit Enter to skip this step. Repeat the process when prompted to re-enter the passphrase.

5. The system generates the key pair and displays the key fingerprint and a randomart image:

Generate an SSH key pair in Windows using ssh-keygen.

Generate SSH Key Pair in Windows via PuTTY

Before OpenSSH was included with Windows, the PuTTY tool was the gold standard for generating SSH keys. This section shows how to generate SSH keys with PuTTY.

Step 1: Install PuTTY

Follow the steps below to install PuTTY on Windows:

1. Open a web browser and navigate to the PuTTY download page. Download the MSI (Windows installer) for your system architecture (x86 or x64).

2. Double-click the downloaded file to start the installation wizard and the PuTTY Welcome screen appears. Click Next to start the installation.

PuTTY welcome screen.

3. Select the destination folder. Use the default installation configuration unless you have a specific need to change it. Click Next to move on to the next screen.

Choose PuTTY installation directory.

4. Select which PuTTY product features to install. If you do not have any specific needs, stick to the defaults. Click Next to proceed to the next screen.

Select which PuTTY features to install.

5. Once the process completes, click Finish to exit the installation wizard.

Complete PuTTY installation.

Step 2: Create SSH Keys with PuTTY

The process outlined below will generate RSA keys, a classic and widely used encryption algorithm. The PuTTY keygen tool offers several other algorithms: DSA, ECDSA, Ed25519, and SSH-1 (RSA). If you require a different encryption algorithm, select the desired option under the Parameters heading before generating the key pair.

The following table sums up the key differences between the available algorithms:

Algorithm Key Size (bits) Security Level Speed Use Case Strengths Weaknesses
RSA 1024 — 4096 High Slow Digital Signatures, TLS Well-studied, widely used. Potentially vulnerable to quantum computing attacks.
DSA 1024 — 3072 Moderate to High Fast Digital Signatures Faster than RSA. Fixed key size.
ECDSA 256 — 521 High Very Fast Digital Signatures Smaller key size, high security. Complex implementation.
Ed25519 256 Very High Very Fast Digital Signatures High security, fast, small keys. Newer, not widely supported.
SSH-1 (RSA) 768 — 2048 Low to Moderate Slow Secure Shell (SSH) Initial SSH protocol. Deprecated, vulnerable.

Follow the steps below to create SSH keys with PuTTY:

1. Press the Windows key and type puttygen. Press Enter to open PuTTY Key Generator.

2. In the PuTTY Key Generator window, click Generate. Move the cursor around in the gray box to fill up the green bar.

Generate an SSH key pair with PuTTY.

3. After the process completes, save the key pair. Click the Save public key button and choose a location to save the key. Give the key a name (e.g., putty_key.pub).

Repeat the process for the private key. You can also set a passphrase to secure the keys additionally.

Save SSH key pair in PuTTY.

Generate SSH Keys in WSL

Windows Subsystem for Linux (WSL) allows users to run a Linux environment without a separate virtual machine or dual booting. To generate SSH keys via WSL, first install the WSL feature on Windows. Our tutorial outlines the step-by-step process for installing WSL on Windows.

After you complete the installation, run the Command Prompt as an administrator and follow the steps below to create an SSH key in WSL:

1. In the WSL terminal, assuming you chose to install Ubuntu in WSL, run the following command:

ssh-keygen -t rsa

2. The system prompts you for the key location and name. Press Enter to accept the default value.

3. The next prompt is the passphrase, which can be left blank. Alternatively, set a passphrase to secure your key by requiring a password whenever it is accessed.

Generate SSH keys with WSL on Windows.

After you enter the necessary information, the utility creates the keys.

Where to Find Generated SSH Keys in Windows

By default, the system saves the keys generated with PuTTY and OpenSSH to C:\Users\your_username\.ssh\id_rsa. To find the keys, open the File Explorer and navigate to that folder.

You should see two files. The identification is saved in the id_rsa file, and the public key is labeled id_rsa.pub. These two files are your SSH key pair.

Note: The public key is identified with the .pub extension. You can use Notepad to see the contents of both the private and public key.

If you used WSL to generate SSH keys, find them in the ~/.ssh directory accessible from the Ubuntu terminal or in the \wsl$\Ubuntu\home\.ssh\ folder accessible with the Windows file explorer.

Conclusion

This article has provided three methods of generating SSH key pairs on a Windows system. Use the SSH keys to connect to a remote system without using passwords.

Next, check out our guide for passwordless SSH login using SSH keys.

Was this article helpful?

YesNo

SSH — это сетевой протокол прикладного уровня, необходимый для обеспечения безопасного подключения, а после и управления операционной системой. Через него можно удаленно выполнять команды в терминале компьютера. Создать удаленное подключение к серверу через SSH можно с помощью паролей или SSH-ключей. В данной статье мы рассмотрим, как создать ключи в операционной системе Windows.

SSH-ключ в Windows — это один из способов безопасного подключения к удаленному серверу. Преимущество данного метода подключения — это отсутствие возможности взлома, как это происходит с паролем.

Для подключения создаются два SSH-ключа:

  • Публичный ключ, хранящийся на сервере в определенном каталоге. Это комбинация символов, которая шифрует данные при обращении к серверу.
  • Приватный — зашифрованный ключ, который располагается на компьютере клиента. Он отвечает за расшифровку полученных данных. При его генерации можно добавить пароль для дополнительной защиты.

Для корректной и полной работы SSHключей необходимо будет отключить аутентификацию по паролю.

После создания SSH-ключей в Windows и из сохранении на сервер, при подключении к серверу будет происходить их проверка. Если публичный ключ соответствует приватному, то подключение выполнится.

Существует два варианта генерации SSH-ключей в Windows. Первый — использование OpenSSH клиента, второй — использование клиента PuTTY. Ниже опишем инструкции по созданию ключей, используя и первый, и второй вариант. В качестве операционной системы будет использоваться Windows 10.

Создать VDS

OpenSSH клиент

  1. Для начала нужно проверить установлен ли OpenSSH клиент на Windows 10. Для этого зайдем в «Параметры», а после перейдем во вкладку «Приложения». Далее нажимаем на ссылку «Дополнительные компоненты», как показано на картинке ниже.

Image1

В открывшемся окне в строку поиска вводим «Клиент OpenSSH». Если в списке он будет найден, то можно сразу приступать к генерации ключей. Если же он отсутствует, то нужно нажать на кнопку «Добавить компонент», а после найти его и выбрать среди всех доступных, используя строку поиска. Далее останется нажать кнопку «Установить» снизу слева и можно переходить ко второму шагу.

  1. Теперь нужно открыть командную строку. Для этого открываем диалоговое окно «Выполнить» (комбинация клавиш Win+R), вводим в строку cmd и нажимаем кнопку «ОК».

Image3

  1. В открывшемся окне вводим команду:
ssh-keygen

После этого запустится процесс генерации. 

В первую очередь пользователю будет предложено ввести путь к папке, в которой будут храниться ключи. Чтобы оставить вариант по умолчанию (.../.ssh/id_rsa), предложенный системой, нужно нажать клавишу «Enter».

Далее пользователю будет предложено ввести ключевое слово к ключу. Чтобы пропустить этот шаг, нажмите также клавишу «Enter» 2 раза.

  1. Проверим, что все ключи успешно сгенерированы. Для этого переходим в соответствующий каталог на своем компьютере. У нас это /.ssh/id_rsa, так как мы оставили все по умолчанию. 

Image2

Как видно по картинке выше, ключи сгенерированы успешно.

Переходим к варианту их создания с помощью клиента PuTTY.

PuTTY

Клиент PuTTY был популярным, когда OpenSSH отсутствовал в Windows. Но и сейчас его не перестают использовать. Он находится в свободном доступе на официальном сайте разработчика. Рассмотрим ниже подробную инструкцию по генерации SSH-ключей на Windows 10 в PuTTY.

  1. Для начала необходимо скачать архив клиента PuTTY с официального сайта.
  2. После его нужно будет разархивировать и запустить файл puttygen.exe от имени администратора.
  3. В открывшемся окне выбираем классический и повсеместно использующийся тип ключа для генерации — RSA. Длину оставляем 2048 бит и нажимаем кнопку «Генерировать».

Image5

  1. Во время генерации нужно водить курсором по серой области внутри окна до заполнения зеленой полоски. Это позволит улучшить защищенность генерируемого ключа, благодаря созданию псевдослучайности.
  2. После успешной генерации нужно сохранить публичный и приватный ключ на компьютере. Для этого создадим папку на диске.

Image4

Ключи успешно созданы и сохранены на локальной машине. На этом этапе их генерация закончена.

Заключение

В данной инструкции были рассмотрены два варианта создания SSH-ключей в Windows. Для подключения к серверу нужно скопировать в него созданный публичный ключ. При попытке соединиться с сервером будет происходить проверка публичного ключа на стороне сервера с приватным на стороне клиента. Если вы пользуетесь облачными серверами Timeweb Cloud, то можете добавить сгенерированный публичный ключ в разделе «SSH-ключи» в панели управления. 

В этой статье мы настроим SSH аутентификацию в Windows по RSA или EdDSA ключам для безопасного доступа к удаленным компьютерам/серверам. Рассмотрим, как сгенерировать открытый и закрытый ключи (сертификаты) в Windows и настроить сервер OpenSSH в Windows 10/11 и Windows Server 2019/2022 для аутентификации по ключам (без паролей).

Аутентификация по SSH ключам широко используется в мире Linux, а в Windows этот функционал появился относительно недавно. Идея заключается в том, что на SSH сервере добавляется открытый ключ клиента и при подключении сервер проверяет наличие соответствующего закрытого ключа у клиента. Таким образом удаленный пользователь может аутентифицироваться в Windows без ввода пароля.

Содержание:

  • Генерация SSH ключей на клиенте Windows
  • Настройка OpenSSH в Windows для авторизации по ключам
  • Вход по SSH ключу для локальных администраторов Windows

Генерация SSH ключей на клиенте Windows

На клиентском, компьютере, с которого вы будет подключаетесь к удалённому серверу Windows с OpenSSH, вам нужно сгенерировать пару ключей (открытый и закрытый). Закрытый ключ хранится на клиенте (не отдавайте его никому!), а открытый ключ нужно скопировать в файл authorized_keys на SSH сервере. Чтобы сгенерировать SSH ключи на клиенте Windows, вы должны установить клиент OpenSSH.

В Windows 10/11 и Windows Server 2019/2022 клиент OpenSSH устанавливается как отдельный встроенный компонент с помощью PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

Запустите обычную (непривилегированную сессию PowerShell) и сгенерируйте пару ED25519 ключей:

ssh-keygen -t ed25519

По умолчанию утилита ssh-keygen генерирует ключи RSA 2048. В настоящий момент вместо RSA ключей рекомендуется использовать именно ED25519.

Утилита попросит вас указать пароль для защиты закрытого ключа. Если вы укажете пароль, то каждый раз при использовании этого ключа для SSH авторизации, вы должны будете вводить этот пароль. Я не стал указывать пароль для ключа (не рекомендуется).

windows ssh-keygen генерация пары ssh ключей

Generating public/private ed25519 key pair. Enter file in which to save the key (C:\Users\myuser/.ssh/id_ed25519):  

Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in C:\Users\myuser/.ssh/id_ed25519. Your public key has been saved in C:\Users\myuser/.ssh/id_ed25519.pub. The key fingerprint is: SHA256:C2wXeCQSUcJyq0 myuser@computername The key's randomart image is: +--[ED25519 256]--+ | ..*O=..o. | +----[SHA256]-----+

Утилита ssh-keygen создаст каталог .ssh в профиле текущего пользователя Windows (%USERPROFILE%\.ssh) и сгенерирует 2 файла:

  • id_ed25519
    – закрытый ключ (если вы сгенерировали ключ типа RSA, файл будет называться
    id_rsa
    )
  • id_ed25519.pub
    – публичный ключ (аналогичный RSA ключ называется
    id_rsa.pub
    )

После того, как ключи созданы, вы можете добавить закрытый ключ в службу SSH Agent, которая позволяет удобно управлять закрытыми ключами и использовать их для аутентификации.

SSH Agent может хранить закрытые ключи и предоставлять их в контексте безопасности текущего пользователя. Запустите службу ssh-agent и настройте автоматический запуск с помощью PowerShell команд управления службами:

Set-service ssh-agent StartupType ‘Automatic’

Start-Service ssh-agent

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

ssh-add "C:\Users\user\.ssh\id_ed25519"

Identity added: C:\Users\kbuldogov\.ssh\id_ed25519 (kbuldogov@computername)

добавить ключ в ssh агент windows

Или так:

ssh-add.exe $ENV:UserProfile\.ssh\id_ed25519

Настройка OpenSSH в Windows для авторизации по ключам

SSH сервер (в этом примере это удаленный компьютер с Windows 11 и настроенной службой OpenSSH).

Скопируйте файл id_ed25519.pub в каталог .ssh профиля пользователя, под которым вы будете подключаться к SSH серверу. Например, у меня в Windows 11 создан пользователь user1, значит я должен скопировать ключ в файл C:\Users\user1\.ssh\authorized_keys.

В данном примере подразумевается, что user1 это обычная учетная запись пользователя без прав локального администратора на компьютере с сервером SSH.

Если каталог .ssh в профиле отсутствует, его нужно создать вручную.

файл с открытым ключом на сервере ssh authorized_keys

Можно скопировать ключ на SSH сервер с клиента с помощью SCP:

scp C:\Users\youruser\.ssh\id_rsa.pub [email protected]:c:\users\user1\.ssh\authorized_keys

В один файл authorized_keys можно добавить несколько открытых ключей.

По умолчанию в OpenSSH сервере в Windows отключена аутентификация по ключам. Вы можете проверить это в конфигурационном файле sshd_config. Проще всего получить список разрешенных способов аутентификации в OpenSSH с помощью такой PowerShell команды (Select-String используется как аналог grep в PowerShell):

cat "C:\ProgramData\ssh\sshd_config"| Select-String "Authentication"

#PubkeyAuthentication yes
#HostbasedAuthentication no
# HostbasedAuthentication
 PasswordAuthentication yes
#GSSAPIAuthentication no

включить ssh аутентфикацию по ключам в windows

В этом примере строка PubkeyAuthentication закомментирована, значит этот способ аутентификации отключен.

Откройте файл sshd_config с помощью блокнота, раскоментируйте строку:

Notepad C:\ProgramData\ssh\sshd_config

PubkeyAuthentication yes

параметр PubkeyAuthentication yes в файле sshd_config

Также в конфигурационном файле sshd_config придется отключить режим StrictModes. По умолчанию этот режим включен и запрещает аутентификацию по ключам, если закрытый и открытый ключ недостаточно защищены. Раскомментируйте строку
#StrictModes yes
, измените на
StrictModes no
.

sshd_config отключить StrictModes

Сохраните файл и перезапустите службу sshd:

Restart-Service sshd

Теперь вы можете подключиться к SSH серверу без ввода пароля пользователя. А если вы не задали пароль (passphrase) для закрытого ключа, вы сразу автоматически подключитесь к вашему удаленному серверу Windows.

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

ssh (username)@(имя или IP адрес SSH сервера)

Например,

ssh [email protected]

Это означает, что вы хотите подключиться к удаленному SSH серверу с адресом 192.168.1.90 под учетной записью admin. Служба SSH Agent автоматически попытается использовать для авторизации сохраненный ранее закрытый ключ.

  • Если вы не хотите использовать ssh-agent для управления ключами, вы можете указать путь к закрытому ключу, который нужно использовать для SSH аутентификации:
    ssh [email protected] -i "C:\Users\user\.ssh\id_ed25519"
  • Для подключения с помощью учетной записи пользователя из домена Active Directory используется формат:
    ssh [email protected]@168.1.90 -i <private_key_absolute_path>

первое подключение к windows по ssh добавить отпечаток ключа

При первом подключении нужно добавить отпечаток ключа SSH сервера в доверенные. Наберите yes -> Enter.

The authenticity of host '192.168.1.90 (192.168.1.90)' can't be established.
ECDSA key fingerprint is SHA256:LNMJTbTS0EmrsGYTHB3Aa3Tisp+7fvHwZHbTA900ofw.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

Информацию по аутентификации в Windows с помощью SSH ключей можно найти в журнале события. В современных версиях OpenSSH логи пишутся не в текстовые файлы, а в отдельный журнал Event Viewer (Application and services logs -> OpenSSH -> Operational).

При успешном подключении с помощью ключа в журнале появится событие:

EventID 4
sshd: Accepted publickey for locadm from 192.168.14.1 port 55772 ssh2: ED25519 SHA256:FEHDWM/J74FbIzCCoJNbh14phS67kQgh7k8UrKPSvCM

событие ssh аутентфикации по ключу в event viewer windows 11

Если вы не смогли подключиться к вашему SSH серверу по RSA ключу, и у вас все равно запрашивается пароль, скорее всего пользователь, под которым вы подключаетесь, входит в группу локальных администраторов сервера (SID группы S-1-5-32-544). Об этом далее.

ssh подключение по ключу под администратором

Вход по SSH ключу для локальных администраторов Windows

В OpenSSH используются особые настройки доступа по ключам для пользователей с правами локального администратора Windows.

В первую очередь, вместо ключа authorized_keys в профиле пользователя нужно использовать файл с ключами C:\ProgramData\ssh\administrators_authorized_keys. Вам нужно добавить ваш ключ в этот текстовый файл (в целях безопасности права на этот файл должны быть только у группы Administrators и SYSTEM).

файл administrators_authorized_keys ключи для ssh входа под локальными администраторами

Вы можете изменить NTFS права на файл с помощью:

  • утилиты icacls:
    icacls.exe "C:\ProgramData\ssh\administrators_authorized_keys" /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F
  • или с помощью PowerShell командлетов get-acl и set-acl:
    get-acl "$env:programdata\ssh\ssh_host_rsa_key" | set-acl "$env:programdata\ssh\administrators_authorized_keys"

настройка ntfs прав доступа к файлу administrators_authorized_keys для ssh доступа по ключам в windows

После этого SSH аутентификация по ключам работает даже при отключенном режиме StrictModes

alert]Чтобы использовать ключ authorized_keys из профиля пользователя, и не переносить данные открытого ключа в файл administrators_authorized_keys, вы можете закомментировать строку в файле конфигурации OpenSSH (C:\ProgramData\ssh\sshd_config).

Закомментируйте строки:

#Match Group administrators
# AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

Match Group administrators AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

Дополнительно в файле sshd_config вы можете запретить SSH подключение по паролю по паролю:

PasswordAuthentication no

После сохранения изменений в файле sshd_config не забудьте перезапустить службу sshd.

restart-service sshd

Если вы установили PasswordAuthentication no, и некорректно настроите аутентификацию по ключам, то при подключении по ssh будет появляться ошибка:

[email protected]: Permission denied (publickey,keyboard-interactive).

ошибка ssh аутентфикации в windows по ключу Permission denied publickey keyboard interactive

В OpenSSH на Linux доступна опция PermitRootLogin, позволяющая ограничить доступ к SSH серверу под аккаунтом root. В Windows OpenSSH эта директива не доступна и для ограничения доступа администраторов нужно использовать параметр DenyGroups.

Итак, вы настроили SSH аутентификацию в Windows по открытому RSA-ключу (сертификату). Теперь вы можете использовать такой способ аутентификации для безопасного доступа к удаленным северам, автоматического поднятия проброса портов в SSH туннеле, запуска скриптов и других задачах автоматизации.

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Оптимальный браузер для windows 7
  • Mediatek mt7921 driver windows 10
  • Активатор office 2010 для windows 10 torrent
  • Активация windows 7 профессиональная ключик для активации
  • Windows чтение разделов linux