SSH является неотъемлемым инструментом для администрирования серверов. Для того чтобы добавить функциональность на ваш Windows Server 2016, рекомендуется использовать OpenSSH. Эта статья поможет вам в установке и настройке.
1. Загрузка дистрибутива OpenSSH:
Перейдите по ссылке https://github.com/PowerShell/Win32-OpenSSH/releases Здесь хранятся все версии OpenSSH для Windows. Скачайте актуальную для вашей системы версию. На момент написания этой статьи последняя доступная версия была v9.2.2.0p1-Beta, представленная в виде файла OpenSSH-Win64.zip
.
2. Распаковка и установка дистрибутива OpenSSH
Вы можете вручную создать директорию C:\Program Files\OpenSSH
и распаковать в неё содержимое загруженного архива.
Или же, запустите PowerShell с правами администратора и выполните следующие команды для установки:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$installDir = "C:\Program Files\OpenSSH"
if (-not (Test-Path $installDir)) {
mkdir $installDir
}
cd $installDir
$downloadLink = "https://github.com/PowerShell/Win32-OpenSSH/releases/download/v9.2.2.0p1-Beta/OpenSSH-Win64.zip"
Invoke-WebRequest -Uri $downloadLink -OutFile .\openssh.zip
Expand-Archive .\openssh.zip -DestinationPath $installDir
Move-Item "C:\Program Files\OpenSSH\OpenSSH-Win64\*" "C:\Program Files\OpenSSH\"
Remove-Item "C:\Program Files\OpenSSH\OpenSSH-Win64" -Force -Recurse
Remove-Item .\openssh.zip
После этого нужно включить эту службу следующей командой:
setx PATH "$env:path;$installDir\" -m
Теперь установим службу sshd.
powershell.exe -ExecutionPolicy Bypass -File install-sshd.ps1
3. Настройка сетевого доступа.
OpenSSH по умолчанию использует порт TCP 22. Чтобы разрешить входящие соединения, необходимо добавить соответствующее правило в брандмауэр Windows:
New-NetFirewallRule -Protocol TCP -LocalPort 22 -Direction Inbound -Action Allow -DisplayName SSH
Дополнительно, вы можете сделать это вручную через графический интерфейс, используя инструмент Windows Firewall with Advanced Security
.
-
Запуск службы OpenSSH.
Для управления службами Windows используйте services.msc
. Откройте его, найдите службу «OpenSSH SSH Server». В настройках этой службы выберите автоматический запуск и активируйте её.
5. Проверка.
Чтобы убедиться, что служба работает корректно и порт 22 слушается, выполните:
netstat -a | findstr "22"
Если 22 порт активен, это означает, что ваш сервер теперь готов к приему SSH-соединений.
6. Тестирование SSH соединения:
Теперь давайте попробуем подключиться к вашему серверу через SSH. Используйте любой SSH-клиент (например, PuTTY или встроенный SSH-клиент в вашей ОС) и попробуйте установить соединение с вашим сервером, указав его IP-адрес и порт 22.
7. Дополнительная настройка дистрибутива OpenSSH:
После успешного тестирования рекомендуется настроить аутентификацию по ключам для повышения безопасности. Это также позволит вам автоматически подключаться к серверу без ввода пароля.
В заключение, OpenSSH — это надежный и безопасный способ установить SSH-сервер на вашем Windows Server 2016. С его помощью вы можете безопасно и удобно управлять своим сервером удаленно.
Также предлагаем рассмотреть другие полезные статьи:
- Как поднять OpenSSH на Windows 2019
- Подключение к VPS серверу по SSH ключу
- Как поднять OpenSSH на Windows 2012
You might find it useful to install OpenSSH on your Windows server. Running SSH on your Windows server means that you can transfer files using Secure Copy (SCP) or SFTP. Aside from SCP and SFTP, you can open a secure Powershell shell or a Bash shell if Windows Subsystem for Linux (WSL) is enabled on your Windows server.
By default, you will enter into a Windows CMD shell when you connect to the server using SSH.
This guide will explain the steps to install and configure OpenSSH in Windows Server 2016. It would be best if you were prepared to log in to your Hostwinds Windows Server to continue with this guide.
Step 1: Download and Install OpenSSH
Start by accessing your server via RDP (from Mac), and download the latest release of OpenSSH (OpenSSH-Win64.zip).
Locate the downloaded file, right-click it, and Extract All to C:\Program Files\OpenSSH-Win64.
Optional: To change the default SSH port to something other than 22, select the sshd_config_default file in the OpenSSH folder and open with a text editor:
Uncomment Port 22 and change it to your desired port, then save the file:
End optional step.
Next, search for and right-click Powershell to Run as administrator:
Modify the Path system environment variable by running the command:
setx PATH "$env:path;C:\Program Files\OpenSSH-Win64" -m
You should see the following output:
SUCCESS: Specified value was saved.
Next, change to the OpenSSH directory:
cd "C:\Program Files\OpenSSH-Win64"
Then run the install script:
.\install-sshd.ps1
Next, enable automatic startup and start sshd and ssh-agent:
Set-Service sshd -StartupType Automatic; Set-Service ssh-agent -StartupType Automatic; Start-Service sshd; Start-Service ssh-agent
Step 2: Allow Access in Windows Firewall
Start by opening Control Panel > Windows Firewall:
Select Advanced Settings on the left-hand side, then select Inbound Rules > New Rule…:
Under Rule Type, select Custom > Next.
Under Program, select All programs > Next.
Under Protocols and Ports, enter your desired SSH port with the following selections:
Under Scope, let the rule apply to Any IP address for remote and local IP addresses, then Next.
Under Action, select Allow the connection > Next.
Under Profile, leave Domain, Private, and Public checked > Next.
Lastly, name the rule and select Finish.
Now you can access your Windows server using SSH!
Prerequirements
Windows Server 2016 VM must be created,
allow_ping_ssh_rdp security group must be allocated,
Floating IP address must be associated.
What We Are Going To Do
Download and install OpenSSH,
Allow access in Windows Firewall,
Connect to Windows via SSH from Linux or Windows,
Access files via SFTP.
Download and install OpenSSH
Log in to your VM via RDP
Download the newest OpenSSH server from GitHub ( https://github.com/PowerShell/Win32-OpenSSH/releases )
In our case it is v8.1.0.0p1-Beta, 64-bit version.
If you can not download the file you can change security settings.
Go to “Control Panel” → “Network and Internet” → “Internet Options” and choose “Security” tab.
Click the Custom level… button.
Find the “Downloads” section and change the “File download” option to “Enable” then click OK.
Confirm by clicking Yes then click Apply.
Now you can download the file.
-
Open the downloaded file and copy the “OpenSSH-Win64” folder to “C:Program Files”.
-
Go to “C:Program FilesOpenSSH-Win64” and edit the “sshd_config_default” file.
-
Find and uncomment following lines by removing the “#” at the beginning then save the file.
#Port 22 #PasswordAuthentication yes
After the changes it should be:
Port 22 PasswordAuthentication yes
6. Now you have to modify system environment variable.
To do it run Windows PowerShell as administrator …
… and type the following command:
setx PATH "$env:path;C:\Program Files\OpenSSH-Win64" -m
You should see the output “SUCCESS: Specified value was saved.”.
-
Change to the OpenSSH directory and run the install script.
cd "C:\Program Files\OpenSSH-Win64"; .\install-sshd.ps1
-
Enable automatic startup and start “sshd” and “ssh-agent” services.
Set-Service sshd -StartupType Automatic; Set-Service ssh-agent -StartupType Automatic; Start-Service sshd; Start-Service ssh-agent
Allow access in Windows Firewall
We have to add new firewall rule to open port which we will use to connect via SSH, default is 22.
To add the rule just run the following command in Windows PowerShell.
New-NetFirewallRule -DisplayName "OpenSSH-Server-In-TCP" -Direction Inbound -LocalPort 22 -Protocol TCP -Action Allow
Connect to Windows via SSH
From Linux
Connect to the VM by typing the following command in terminal. Remember to type your VM’s IP address.
ssh Administrator@<your-vm-ip-address>
Type the password.
If you are connected you should be in Administrator’s home directory.
From Windows (via Putty)
Open Putty and create new session. Complete the fields as below.
Host Name for IP address: Administrator@<your-vm-ip-address>
Port: 22
Connection type: SSH
Saved Sessions: <your-vm-name>
Click Save button.
Double click on your new saved session to connect then click Yes.
Now you are connected to your Windows VM via SSH.
Accessing files via SFTP
WinSCP
Prerequirements
WinSCP must be installed
Open WinSCP and click New Session.
Complete fields as below and click Save.
Host name: <your-vm-ip-address>
Port number: 22
User name: Administrator
Password: <your-password>
Click OK. You can also save your password.
Confirm by clicking Yes.
Now you can browse your files.
How to Install OpenSSH Server/Client on Windows Server 2016 1607 or Before
OpenSSH is the premier connectivity tool for remote login with the SSH protocol. It encrypts all traffic to eliminate eavesdropping, connection hijacking, and other attacks. In addition, OpenSSH provides a large suite of secure tunneling capabilities, several authentication methods, and sophisticated configuration options. Installation of OpenSSH server/client on Windows 2016 1709 onward is really easy. its just few powershell commands away from using it but for older versions it can be a time wasting activity. The easiest way to install is still very long but I would to wrap in few basic steps:
Download OpenSSH
First you need to Download OpenSSH using the attached URL. A zip file will be downloaded on your desired system. Unzip it and copy it under Windows\system32 directory.
Open PowerShell ISE
Open PowerShell ISE with administrative privileges so that you can run the desired commands without any problem. Change the directory to c:\windows\system32\openssh
Run the Commands
First you need to modify the required permission so run the under given command from OpenSSh Directory. The commands are given in the picture below:
Run the commands in the given order and OpenSSH server will be installed on the Windows Server 2016 1607 or earlier version.
Environment Variables
Copy the directory path and set the system environment variables so that the commands can work without giving the exact path. You can use PowerShell commands to set the path or go to system settings and manually set the path.
Start the services
Change the service startup type from manual to automatic and start the service to use OpenSSH server.
Windows Firewall Settings
SSH works on TCP port 22 so you need to open in-bound port in Windows firewall so that in-coming connections can be accepted. Opening firewall port is pretty simple and I think there is no need to share any command or process to do it.
Thanks for visiting. I hope you like the post.
Microsoft have released their OpenSSH port for Windows Server and Windows 10 back in 2015. Here is how to install the OpenSSH Server on Windows Server 2022, 2019 and 2016.
In this small tutorial, I’ll show you how to manually install OpenSSH in Windows Server (all versions). You’ll notice I’m not using PowerShell’s Add-WindowsCapability
cmdlet, because it errors out on unsupported platforms. And I want to be able to customize the sshd installation directory. If you follow this post, you can install Microsoft OpenSSH Server on Windows Server 2022 through even Windows Server 2012 R2, in a destination folder of your choosing. Sweet
Please note that a lot has changed in recent years, like Microsoft releasing .msi
Windows Installer installation files, and you no longer have to rely on PowerShell Add-WindowsCapability
or .zip
files. Wherever possible, use the OpenSSH .msi installation option.
Want to know how to extract files from an MSI package file?
Prerequisites
In order to be able to install OpenSSH on Windows, you need the software. Doh!
- Download the latest OpenSSH for Windows release from GitHub: https://github.com/PowerShell/Win32-OpenSSH/releases (OpenSSH-Win64.zip for example).
Tunnel RDP through SSH & PuTTY, or learn how to share OpenSSH keys with WSL in Windows 10
Install «Windows for OpenSSH» using PowerShell
- Unblock the downloaded OpenSSH archive if necessary:
Unblock-File .\Downloads\OpenSSH-Win64.zip
- Extract the archive:
Expand-Archive .\Downloads\OpenSSH-Win64.zip -DestinationPath .
- Copy the OpenSSH-Win64 folder to your desired location, e.g c:
Copy-Item -Recurse .\OpenSSH-Win64\ 'C:\'
- The libcrypto.dll file has to be accessible for all users:
&icacls C:\OpenSSH-Win64\libcrypto.dll /grant Everyone:RX
- Run
install-sshd.ps1
to create the OpenSSH Authentication Agent and OpenSSH SSH Server services. It also sets some permissions and registers an Event Tracing (ETW) provider. - Change the service startup to Automatic. The OpenSSH SSH Server service is set to Manual startup, not automatic:
&sc.exe config sshd start= auto
,&sc.exe config ssh-agent start= auto
- Start the OpenSSH Authentication Agent and SSH Server services:
&sc.exe start sshd
,&sc.exe start ssh-agent
- Make sure your Windows Defender Firewall is open for port 22, rule OpenSSH-Server-In-TCP must be enabled. If this rule is not available, manually create it:
New-NetFirewallRule `
-Name sshd `
-DisplayName 'OpenSSH SSH Server' `
-Enabled True `
-Direction Inbound `
-Protocol TCP `
-Action Allow `
-LocalPort 22 `
-Program "C:\Windows\System32\OpenSSH\sshd.exe"
Replace C:\Windows\System32\OpenSSH\sshd.exe
with the actual path to the sshd.exe (C:\OpenSSH\sshd.exe
, if you followed these instructions). Or go to Control Panel > System and Security > Windows Firewall > Advanced Settings > Inbound Rules and add a new rule for port 22.
Let’s connect!
PS C:\> ssh -l janreilink localhost
Retrieve SSH public key from Active Directory for SSH authentication
Install Win32-OpenSSH Server using MSI Installer
If you have downloaded the .msi
Windows Installer MSI-file of Microsoft OpenSSH (OpenSSH-Win64-v8.9.1.0.msi
for example), you can install OpenSSH server and client easily. The following command installs both OpenSSH Server and OpenSSH Client:
& msiexec.exe /i path to OpenSSH-Win64-v8.9.1.0.msi
This, however installs OpenSSH in the location C:\Program Files\OpenSSH
, and doesn’t update your $env:path
environment variable. There are some other caveats. You can follow my guide «install Microsoft OpenSSH Client properly in Windows 11 and Windows 10 to support FIDO/U2F security keys» on Windows Server 2022 / 2019 to install and configure OpenSSH Server and Client using .msi installer files.
sshd_config
Often you not only need to install OpenSSH, you also need to configure it. For this, OpenSSH on Windows uses an mechanism where the default sshd_config
(called «sshd_config_default
«) is located in the directory to where you’ve unpacked the OpenSSH-Win64.zip
archive. When you start the service, the file is copied to C:\ProgramData\ssh\sshd_config
.
In Windows, sshd reads configuration data from %programdata%\ssh\sshd_config by default, or a different configuration file may be specified by launching sshd.exe with the -f parameter. If the file is absent, sshd generates one with the default configuration when the service is started.
https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh\_server\_configuration#windows-configurations-in-sshd\_config
So you can either make you configuration in the sshd_config_default
file, that is copied when you start the service for the first time, or you start and stop OpenSSH, edit C:\ProgramData\ssh\sshd_config
and restart OpenSSH again.
Configure your Windows 11/10 and WSL 2 DevOps environment
Install OpenSSH in Windows Server 2012
OpenSSH Server on Windows Server 2012 R2, you said? Yes, you can use the same method to install OpenSSH in Windows Server 2012 R2 (version 6.3.9600). Here is a screenshot of connecting to sshd on Windows version 6.3.9600:
Conclusion and giveaway
In this post I showed you how you can install OpenSSH server in various Windows Server versions, using the downloaded .zip file archive and PowerShell. You can use this approach to customize and streamline your Microsoft OpenSSH Server environment. This goes very well with SSH keys stored in Active Directory. If you want to use FIFO/U2F security keys like YubiKey in Windows OpenSSH, follow that guide.
In an other post I’ll show you how to install OpenSSH Client in Windows 11 and Windows 10. Using the OpenSSH-Win64-v8.9.1.0.msi file.