- Доступ к сетевым приложениям с помощью WSL
- Доступ к сетевым приложениям Linux из Windows (localhost)
- Доступ к сетевым приложениям Windows из Linux (IP-адрес основной системы)
- Подключение через удаленные IP-адреса
- Доступ к дистрибутиву WSL 2 из локальной сети (LAN)
- Доступ по протоколу IPv6
- 3 Ways to Use SSH on Windows to Log Into Linux Server
- What’s SSH?
- Method 1: Windows 10’s Built-in SSH Client
- Method 2: Use SSH in Windows Subsystem for Linux
- Method 3: Use Putty
- How to Set Up SSH Key on Windows 10 (Optional)
- Next Step
- Accessing network applications with WSL
- Accessing Linux networking apps from Windows (localhost)
- Accessing Windows networking apps from Linux (host IP)
- Connecting via remote IP addresses
- Accessing a WSL 2 distribution from your local area network (LAN)
- IPv6 access
Доступ к сетевым приложениям с помощью WSL
При работе с сетевыми приложениями (будь то получение доступа к сетевому приложению Linux из приложения Windows или получение доступа к сетевому приложению Windows из приложения Linux) необходимо учитывать несколько моментов. Вам может потребоваться определить IP-адрес используемой виртуальной машины, который будет отличаться от IP-адреса локального физического компьютера.
Доступ к сетевым приложениям Linux из Windows (localhost)
Если вы создаете сетевое приложение (например, приложение, работающее на NodeJS или SQL Server) в дистрибутиве Linux, вы можете получить к нему доступ из приложения Windows (например, используя Microsoft Edge или Chrome) с помощью localhost (как обычно это и происходит).
Доступ к сетевым приложениям Windows из Linux (IP-адрес основной системы)
Если вы хотите получить доступ к сетевому приложению, работающему в Windows (например, к приложению, работающему на NodeJS или SQL Server) из дистрибутива Linux (напр., Ubuntu), необходимо использовать IP-адрес основной системы. Хотя это происходит и нечасто, для этого можно выполнить следующие действия.
- Получите IP-адрес основной системы, выполнив следующую команду из дистрибутива Linux: cat /etc/resolv.conf
- Скопируйте IP-адрес в строке, начинающейся с nameserver .
- Подключитесь к любому серверу Windows, используя скопированный IP-адрес.
На изображении ниже показан пример подключения к серверу Node.js под управлением Windows через cURL.
Подключение через удаленные IP-адреса
При использовании удаленных IP-адресов для подключения к приложениям они будут рассматриваться как подключения из локальной сети (LAN). Это означает, что необходимо убедиться, что приложение может принимать подключения по локальной сети.
Например, может потребоваться привязать приложение к 0.0.0.0 вместо 127.0.0.1 . В примере приложения Python, использующего Flask, это можно сделать с помощью команды app.run(host=’0.0.0.0′) . При внесении этих изменений не забывайте о безопасности, так как это позволит устанавливать подключения из вашей локальной сети.
Доступ к дистрибутиву WSL 2 из локальной сети (LAN)
При использовании дистрибутива WSL 1, если к компьютеру можно получить доступ из локальной сети, то приложения, работающие в WSL, могут быть также доступны в локальной сети.
Это нетипичная ситуация в WSL 2. В WSL 2 имеется виртуализированный адаптер Ethernet с собственным уникальным IP-адресом. В настоящее время для включения этого рабочего процесса необходимо выполнить те же действия, что и для обычной виртуальной машины. (Мы ищем способы улучшить это взаимодействие.)
Ниже приведен пример команды Windows для добавления прокси-сервера порта, который прослушивает порт 4000 на узле и подключает его к порту 4000 к виртуальной машине WSL 2 с IP-адресом 192.168.101.100.
netsh interface portproxy add v4tov4 listenport=4000 listenaddress=0.0.0.0 connectport=4000 connectaddress=192.168.101.100
Доступ по протоколу IPv6
В настоящее время дистрибутивы WSL 2 не могут обращаться к IPv6-адресам. Мы работаем над добавлением этой возможности.
3 Ways to Use SSH on Windows to Log Into Linux Server
This tutorial is going to show you 3 ways to log into Linux server on Windows via SSH.
What’s SSH?
SSH stands for Secure Shell, which was invented in 1995 to replace the insecure Telnet (Telecommunication Network). It’s now the primary way for system administrators to securely log into remote Linux servers over the public Internet. Although it looks and acts the same as Telnet, all communications over the SSH protocol is encrypted to prevent packet sniffing.
If you are running a Linux or Mac computer, SSH client is installed by default. You can open up a terminal window and run the ssh command like below to connect to a remote Linux server.
Now let’s discuss how to use SSH on Windows.
Method 1: Windows 10’s Built-in SSH Client
The Microsoft PowerShell team decided to port OpenSSH (both the client and the server) to Windows in 2015. It finally arrived in Windows 10’s Fall Creator Update in 2017 and is enabled by default in the April 2018 Update.
To use the OpenSSH client on Windows 10, simply open a PowerShell window or a command prompt window and run the ssh command. For example, if I want to connect to my Ubuntu desktop in the LAN, I would run
linuxbabe is the username on my Ubuntu desktop and 192.168.0.101 is the private IP address for my Ubuntu desktop. The first time you connect to a Linux computer, you will be prompted to accept the host key. Then enter your password to login. After login, you can run Linux commands to do administrative tasks.
Note that if you want to paste a password into the PowerShell window, you need to right-click the mouse and press Enter.
To log out from the Linux box, run the exit command or press Ctrl+D .
The default font size in PowerShell Window is very small. To change it, right-click the titlebar and select properties , then you can change the font size, and the background color.
Method 2: Use SSH in Windows Subsystem for Linux
Windows Subsystem for Linux (WSL) enables you to run native Linux command-line tools directly on Windows 10. If you are a system administrator, WSL is probably an overkill for just using SSH because it would install and run a Linux distro (without graphical user interface) on your Windows 10 desktop. WSL is created for web developers or those who need to work on open-source projects. You can use not only SSH but also other Linux command line tools (Bash, sed, awk, etc).
Open the Microsoft Store and enter WSL in the search box. Select Run Linux on Windows and install a Linux distro of your choice.
For example, I choose Ubuntu and click the Get button to install it.
Once your Linux distro is installed, open the Control Panel and select Programs -> Turn Windows features on or off . Tick on the checkbox of Windows Subsystem for Linux to enable this feature. (You may need to reboot your Windows PC for this change to take effect.)
Next, you can launch the Linux distro from the start menu by search the distro’s name. The first time you launch it, you need to create a user and set a password.
After that, you can use the ssh command like below to connect to a Linux server or PC that runs a SSH server.
Method 3: Use Putty
Putty is a well-known and the most popular SSH client on Windows before the arrival of Windows OpenSSH client and Windows Subsystem for Linux. To use SSH with Putty, you need to download the Putty program from the official website and install it.
Launch Putty from the Start menu. Then enter the IP address or hostname of the Linux box and click the Open button to connect to it.
Accept the host key and you will be prompted to enter the username and password.
Please note that when you type in your password, the cursor doesn’t move, but it’s actually accepting your password. To paste text into Putty, first press Ctrl+C to copy the text, then go to Putty window and press the right button of your mouse.
How to Set Up SSH Key on Windows 10 (Optional)
There’re mainly two ways of authenticating user login with OpenSSH server:
- password authentication
- public-key authentication: also known as passwordless SSH login because you don’t need to enter your password.
To set up public-key authentication on Windows 10, follow the instructions below.
Open Windows Powershell, and run the following command to generate SSH keypair.
- -t stands for type . The above command generates an RSA type keypair. RSA is the default type.
- -b stands for bits . By default, the key is 3072 bits long. We use a 4096 bits key for stronger security.
When asked which file to save the key, you can simply press Enter to use the default file. Next, you can enter a passphrase to encrypt the private key, but you will need to enter this passphrase every time when you log into the Linux server. If you don’t want it, you can press Enter, so it will have no passphrase.
- The private key (your identification) will be saved in the .ssh/id_rsa file under your user directory.
- The public key will be saved in the .ssh/id_rsa.pub file.
Now we need to upload the public key to remote Linux server. You can display the public key in the Powershell with the following command.
Then log in to your server via password authentication, and run the following command to create a .ssh directory under your home directory.
Create the authorized_hosts file
sudo nano ~/.ssh/authorized_keys
Copy your SSH public key and paste it to this file. Save and close the file. To save a file in Nano text editor, press Ctrl+O , then press Enter to confirm. To close a file, press Ctrl+X .
Next, change the permission of this file.
sudo chmod 600 ~/.ssh/authorized_keys
Log out of your Linux server.
Now you can SSH into your server without entering a password.
Next Step
I hope this article helped you use SSH on Windows. You might also want to protect SSH service from hacking, I recommend setting up public-key authentication or two-factor authentication.
Also, you can enable automatic security updates on your Linux server to patch vulnerabilities.
If you want FTP access to the Ubuntu server, you can set up pure-FTPd server.
As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂
Accessing network applications with WSL
There are a few considerations to be aware of when working with networking apps, whether you are accessing a Linux networking app from a Windows app or accessing a Windows networking app from a Linux app, you may need to identify the IP address of the virtual machine you are working with, which will be different than the IP address of your local physical machine.
Accessing Linux networking apps from Windows (localhost)
If you are building a networking app (for example an app running on a NodeJS or SQL server) in your Linux distribution, you can access it from a Windows app (like your Edge or Chrome internet browser) using localhost (just like you normally would).
Accessing Windows networking apps from Linux (host IP)
If you want to access a networking app running on Windows (for example an app running on a NodeJS or SQL server) from your Linux distribution (ie Ubuntu), then you need to use the IP address of your host machine. While this is not a common scenario, you can follow these steps to make it work.
- Obtain the IP address of your host machine by running this command from your Linux distribution: cat /etc/resolv.conf
- Copy the IP address following the term: nameserver .
- Connect to any Windows server using the copied IP address.
The picture below shows an example of this by connecting to a Node.js server running in Windows via curl.
Connecting via remote IP addresses
When using remote IP addresses to connect to your applications, they will be treated as connections from the Local Area Network (LAN). This means that you will need to make sure your application can accept LAN connections.
For example, you may need to bind your application to 0.0.0.0 instead of 127.0.0.1 . In the example of a Python app using Flask, this can be done with the command: app.run(host=’0.0.0.0′) . Please keep security in mind when making these changes as this will allow connections from your LAN.
Accessing a WSL 2 distribution from your local area network (LAN)
When using a WSL 1 distribution, if your computer was set up to be accessed by your LAN, then applications run in WSL could be accessed on your LAN as well.
This isn’t the default case in WSL 2. WSL 2 has a virtualized ethernet adapter with its own unique IP address. Currently, to enable this workflow you will need to go through the same steps as you would for a regular virtual machine. (We are looking into ways to improve this experience.)
Here’s an example Windows command to add a port proxy that listens on port 4000 on the host and connects it to port 4000 to the WSL 2 VM with IP address 192.168.101.100.
netsh interface portproxy add v4tov4 listenport=4000 listenaddress=0.0.0.0 connectport=4000 connectaddress=192.168.101.100
IPv6 access
WSL 2 distributions currently cannot reach IPv6-only addresses. We are working on adding this feature.