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!
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
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.
В данном руководстве посмотрим, как настроить подключение по SSH к виртуальному Windows-серверу. Для работы мы будем использовать VPS, работающий на операционной системе Windows Server 2016. Заказ подобного сервера производится в личном кабинете на сайте UltraVDS.
Загрузка и установка OpenSSH
На первом шаге настройки подключения к Windows-серверу по протоколу SSH необходимо установить на него оболочку OpenSSH. В Windows Server 2016 это удобнее осуществить путём загрузки и инсталляции OpenSSH из репозитория на GitHub.
Для этого подключитесь к вашему VDS через RDP и уже с удалённого рабочего стола вашего виртуального сервера перейдите по ссылке. На момент написания данного мануала последней версией OpenSSH на GitHub была версия v9.1.0.0p1-Beta
. Поэтому на ресурсе последней версии необходимо найти и загрузить оттуда архив дистрибутива — файл OpenSSH-Win64.zip
.
После того, как загрузка файла будет завершена, папку OpenSSH-Win64
скопируйте из архива OpenSSH-Win64.zip
в каталог Program Files
.
Далее перейдите в папку OpenSSH-Win64
и при помощи текстового редактора Notepad
отредактируйте файл sshd_config_default
. А именно, в нём необходимо снять комментарии (удалить символ #
) в строке:
#Port 22
И в строке:
#PasswordAuthentication yes
После чего закройте файл sshd_config_default
с сохранением внесённых изменений.
Теперь можно перейти непосредственно к установке OpenSSH. Для этого от имени администратора запустите оболочку PowerShell.
Далее в командной строке PowerShell наберите следующую команду:
setx PATH "$env:path;C:\Program Files\OpenSSH-Win64" -m
При её успешном выполнении вывод команды должен выглядеть как на скриншоте ниже:
Следующая команда осуществляет переход в папку C:\Program Files\OpenSSH-Win64
и запускает скрипт install-sshd.ps1
.
cd "C:\Program Files\OpenSSH-Win64"; .\install-sshd.ps1
В процессе выполнения своих инструкций скрипт дважды запросит разрешение на их запуск. Для проведения успешной установки OpenSSH нажмите R
при каждом запросе.
Первоначальная настройка OpenSSH
Для того, чтобы оболочка OpenSSH была доступна всегда и самостоятельно запускалась при перезагрузке сервера, необходимо запустить службы sshd
и ssh-agent
, а также включить их автоматический старт. Производится это при помощи следующей команды:
Set-Service sshd -StartupType Automatic; Set-Service ssh-agent -StartupType Automatic; Start-Service sshd; Start-Service ssh-agent
На заключительном этапе установки OpenSSH необходимо разрешить в брандмауэре Windows доступ к серверу по протоколу SSH. По умолчанию SSH использует TCP-порт 22. Таким образом, следующей командой нужно будет открыть доступ к данному порту в Windows Firewall.
New-NetFirewallRule -DisplayName "OpenSSH-Server-In-TCP" -Direction Inbound -LocalPort 22 -Protocol TCP -Action Allow
Подключение к VPS по SSH
Теперь можно попробовать подключиться к вашему VPS с использованием протокола SSH. С компьютера, работающего под управлением как Windows, так и одной из операционных систем Linux, подключение производится из командной строки или терминала при помощи команды:
$ ssh your_user_name@your_server_IP
Здесь:
your_user_name
— имя учётной записи, под которой производится подключение к VDS;your_server_IP
— IP-адрес вашего виртуального Windows-сервера.
При первом подключении система предупредит вас о невозможности установления подлинности удалённого хоста. Для того, чтобы рабочая станция, с которой производится подключение получила отпечаток ключа для проверки, необходимо ответить на предупреждение набрав yes
.
При каждом повторном подключении к тому же удалённому серверу SSH будет проверять принятый вами фингерпринт для подтверждения его легитимности.
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.