Ssh connection to linux from windows

Содержание

  1. Что такое SSH?
  2. Способ 1. Встроенный SSH-клиент в Windows 10
  3. Способ 2: использование SSH в подсистеме Windows для Linux
  4. Способ 3: использовать Putty
  5. Завершение

Что такое SSH?

SSH означает Secure Shell – протокол, который был изобретен в 1995 году для замены небезопасного Telnet (телекоммуникационная сеть).

Теперь системный администратор является основным способом безопасного входа на удаленные серверы Linux через общедоступный Интернет.

Хотя он выглядит и действует так же, как Telnet, все коммуникации по протоколу SSH зашифрованы для предотвращения перехвата пакетов.

Если вы используете компьютер с Linux или Mac, SSH-клиент установлен по умолчанию.

Вы можете открыть окно терминала и запустить команду ssh, как показано ниже, для подключения к удаленному серверу Linux.

ssh username@itsecforu.local

Теперь давайте обсудим, как использовать SSH в Windows.

Способ 1. Встроенный SSH-клиент в Windows 10

Группа разработчиков Microsoft PowerShell решила перенести OpenSSH (и клиент, и сервер) на Windows в 2015 году.

Наконец, он появился в Windows 10 Fall Creator Update в 2017 году и по умолчанию включена в обновлении от апреля 2018 года.

Чтобы использовать клиент OpenSSH в Windows 10, просто откройте окно PowerShell или окно командной строки и выполните команду ssh.

Например, если я хочу подключиться к своему рабочему столу Ubuntu в локальной сети, я бы запустил.

ssh cryptoparty@192.168.0.101

cryptoparty – это имя пользователя на моем рабочем столе Ubuntu, а 192.168.0.101 – это частный IP-адрес моего рабочего стола Ubuntu.

При первом подключении к компьютеру с Linux вам будет предложено принять ключ хоста.

Затем введите свой пароль для входа.

После входа в систему вы можете запускать команды Linux для выполнения административных задач.

Чтобы выйти из окна Linux, выполните команду выхода или нажмите Ctrl + D.

Чтобы выйти из окна Linux, выполните команду exit или нажмите Ctrl + D.

Способ 2: использование SSH в подсистеме Windows для Linux

Подсистема Windows для Linux (WSL) позволяет запускать встроенные средства командной строки Linux непосредственно в Windows 10.

Если вы являетесь системным администратором, WSL, вероятно, является излишним просто для использования SSH, поскольку он установит и запустит дистрибутив Linux (без графического интерфейса) на рабочем столе Windows 10.

Kali Linux в подсистеме Windows для Linux

WSL создан для веб-разработчиков или тех, кому нужно работать над проектами с открытым исходным кодом.

Вы можете использовать не только SSH, но и другие инструменты командной строки Linux (Bash, sed, awk и т. д.).

Откройте Microsoft Store и введите WSL в поле поиска. Выберите «Запустить Linux на Windows» и установите дистрибутив Linux по вашему выбору.

Например, я выбрал Ubuntu и нажимаю кнопку Get, чтобы установить ее.

После установки дистрибутива Linux откройте панель управления и выберите «Программы» -> «Включить или отключить функции Windows».

Установите флажок Подсистема Windows для Linux, чтобы включить эту функцию.

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

После этого вы можете использовать команду ssh, как показано ниже, для подключения к серверу Linux или ПК, на котором работает SSH-сервер.

ssh itsecforu@192.168.0.101

Способ 3: использовать Putty

Putty – известный и самый популярный SSH-клиент в Windows до появления клиента Windows OpenSSH и подсистемы Windows для Linux.

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

Запустите Putty из меню «Пуск». Затем введите IP-адрес или имя хоста окна Linux и нажмите кнопку «Open», чтобы подключиться к этом серверу.

Примите ключ хоста, и вам будет предложено ввести имя пользователя и пароль.

См. также:

  • Как использовать команды SSH в командной строке Windows 10
  • 6 команд для очистки терминала Linux

Завершение

Я надеюсь, что эта статья помогла вам использовать SSH в Windows.

Как всегда, если вы нашли эту статью полезной, поделитесь ей, чтобы получить больше советов и рекомендаций. Берегите себя 🙂

The secure shell protocol (SSH) is the most common method for controlling remote machines over the command line in the Linux world. SSH is a true Linux original, and it is also gaining popularity in the Windows world. There is even official Windows documentation for SSH, which covers controlling Windows machines using OpenSSH.

This article describes how to establish an SSH connection from a Windows machine to a Fedora 33 Linux system using the popular open source tool PuTTY.

Ways to use SSH

SSH uses a client-server architecture, where an SSH client establishes a connection to an SSH server. The SSH server is usually running as a system daemon, so it is often called SSHD. You can hardly find a Linux distribution that does not come with the SSH daemon. In Fedora 33, the SSH daemon is installed but not activated.

You can use SSH to control almost any Linux machine, whether it’s running as a virtual machine or as a physical device on your network. A common use case is the headless configuration of embedded devices, including the Raspberry Pi. SSH can also be used to tunnel other network services. Because SSH traffic is encrypted, you can use SSH as a transport layer for any protocol that does not provide encryption by default.

In this article, I’ll explain four ways to use SSH: 1. how to configure the SSH daemon on the Linux side, 2. how to set up a remote console connection, 3. how to copy files over the network, and 4. how to tunnel a certain protocol over SSH.

1. Configure SSHD

The Linux system (Fedora 33 in my case) acts as the SSH server that allows the PuTTY SSH client to connect. First, check the daemon’s SSH configuration. The configuration file is located at /etc/ssh/sshd_config and contains a lot of switches that can be activated by commenting out related lines:

#	$OpenBSD: sshd_config,v 1.100 2016/08/15 12:32:04 naddy Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin

# 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.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

The default configuration, where no line is uncommented, should work for this example. Check whether the SSH daemon is already running by typing systemctl status sshd:

$ systemctl status sshd
● sshd.service - OpenSSH server daemon
   Loaded: loaded (/usr/lib/systemd/system/sshd.service; enabled; vendor preset: enabled)
   Active: active (running) since Fri 2018-06-22 11:12:05 UTC; 2 years 11 months ago
     Docs: man:sshd(8)
           man:sshd_config(5)
 Main PID: 577 (sshd)
    Tasks: 1 (limit: 26213)
   CGroup: /system.slice/sshd.service
           └─577 /usr/sbin/sshd -D -oCiphers=aes256-gcm@openssh.com,chacha20-[...]

If it’s inactive, start it with the systemctl start sshd command.

2. Set up a remote console

On Windows, download the PuTTY installer, then install and open it. You should see a window like this:

PuTTY configuration screen

In the Host Name (or IP address) input field, enter the connection information for your Linux system. In this example, I set up a Fedora 33 virtual machine with a bridged network adapter that I can use to contact the system at the IP address 192.168.1.60. Click Open, and a window like this should open:

PutTTY security alert

This is an SSH security mechanism to prevent a man-in-the-middle attack. The fingerprint in the message should match the key on the Linux system at /etc/ssh/ssh_host_ed25519_key.pub.. PuTTY prints the key as an MD5 hash. To check its authenticity, switch to the Linux system, open a command shell, and enter:

ssh-keygen -l -E md5 -f /etc/ssh/ssh_host_ed25519_key.pub

The output should match the fingerprint shown by PuTTY:

$ ssh-keygen -l -E md5 -f /etc/ssh/ssh_host_ed25519_key.pub
256 MD5:E4:5F:01:05:D0:F7:DC:A6:32 no comment (ED25519)

Confirm the PuTTY Security Alert by clicking Yes. The host system’s fingerprint is now in PuTTYs trust list, which is located in the Windows registry under:

HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\SshHostKeys

Enter your correct login credentials, and you should be on the console in your home directory:

Logged in to SSH

3. Copy files over the network

In addition to the remote console, you can use PuTTY to transfer files via SSH. Look in the installation folder under C:\\Program Files (x86)\\PuTTY and find pscp.exe. You can use this to copy files to and from a Linux system.

Open a command prompt with Windows + R and enter cmd. Copy the file MyFile.txt from your Linux user home directory to your Windows home directory by entering:

C:\"Program Files (x86)"\PuTTY\pscp.exe stephan@192.168.1.60:/home/stephan/MyFile.txt .

To copy a file from the Windows home directory to the Linux user home directory, enter:

C:\"Program Files (x86)"\PuTTY\pscp.exe MyFile.txt stephan@192.168.1.60:/home/stephan/

As you may have already figured out, the copy command’s general structure is:

pscp.exe <source> <target>

4. Tunnel a protocol

Imagine you have a Linux machine that is running an HTTP-based service for some arbitrary application. You want to access this HTTP service from your Windows machine over the internet. Of course, you cannot expose the related TCP port to the public because:

  1. The server is running HTTP, not HTTPS
  2. There is no user management nor login at all

At first glance, it looks like an impossible task to set up this architecture without producing a horrible security flaw. But SSH makes it relatively easy to set up a safe solution for this scenario.

I will demonstrate this procedure with my software project Pythonic. Running as a container, Pythonic exposes two TCP ports: TCP port 7000 (main editor) and TCP port 8000 (the code-server source-code editor).

To install Pythonic on a Linux machine, run:

podman pull pythonicautomation/pythonic
podman run -d -p 7000:7000 -p 8000:8000 pythonic

Switch to your Windows machine, open PuTTY, and navigate to Connection -> SSH -> Tunnels. Add the two TCP ports you want to forward:

  • Source: 7000 / Destination: localhost:7000
  • Source: 8000 / Destination: localhost:8000

Port forwarding in PuTTY

Then go back to the Session section, and establish an SSH connection as you did before. Open a browser and navigate to http://localhost:7000; you should see a screen like this:

Pythonic

You have successfully configured port forwarding!

Warning: If you expose TCP Port 22 to the public, don’t use easy-to-guess login credentials. You will receive login attempts from all over the world trying to access your Linux machine with common, standard credentials. Instead, permit only known clients to log in. This login restriction can be achieved using public-key cryptography, which uses a key pair in which the public key is stored on the SSH host machine, and the private key remains at the client.

Debugging

If you are struggling to connect to your Linux machine, you can follow the processes in your SSH daemon with:

journalctl -f -u sshd

This is how an ordinary log-in process looks like with LogLevel DEBUG :

LogLevel DEBUG output

Learn more

This article barely scratched the surface about ways to use SSH. If you are looking for information about a specific use case, you can probably find it among the tons of SSH tutorials on the internet. I use PuTTY heavily at work because its easy configuration and good interoperability between operating systems make it a Swiss Army knife tool for connectivity solutions.

Creative Commons LicenseThis work is licensed under a Creative Commons Attribution-Share Alike 4.0 International License.

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.

ssh [email protected]

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

ssh [email protected]

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.

ssh windows

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.

windows powershell change font size and background

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.

wsl windows subsystem for linux

For example, I choose Ubuntu and click the Get button to install it.

ubuntu windows subsystem for linux

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.

ssh windows 10

After that, you can use the ssh command like below to connect to a Linux server or PC that runs a SSH server.

ssh [email protected]

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.

ssh windows command line

Accept the host key and you will be prompted to enter the username and password.

ssh windows 10 command line

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.

ssh-keygen -t rsa -b 4096

Where:

  • -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.

ssh key windows

  • 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.

cat .ssh/id_rsa.pub

Then log in to your server via password authentication, and run the following command to create a .ssh directory under your home directory.

sudo mkdir ~/.ssh

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.

exit

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.

  • 2 Simple Steps to Set up Passwordless SSH Login on Ubuntu
  • Set Up SSH Two-Factor Authentication (2FA) on Ubuntu Server

Also, you can enable automatic security updates on your Linux server to patch vulnerabilities.

  • Set Up Automatic Security Update (Unattended Upgrades) on Ubuntu

If you want FTP access to the Ubuntu server, you can set up pure-FTPd server.

  • How to Set Up a Secure FTP Server with Pure-FTPd on Ubuntu

As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂

NOTE: I do a LOT of handholding in this article. I wanted to be sure someone who is less-than-familiar with the Linux Command Line Interface and/or SSH would have no trouble understanding what is going on. Here are some navigation links to more readily find what you need:

  • Install OpenSSH on your Linux Machine
  • Install PuTTY on Your Windows Machine
  • Create Public/Private Key pairs with PuTTYGen
  • Configure PuTTY for Initial Login to Your Linux Machine
  • Your First Login Using Password-based Authentication
  • Add Your Public Key to the Linux Authorized Keys List
  • Configure PuTTY for Key-Based Authentication
  • Connect to Your Linux Machine using Key-Based Authentication
  • Set Key File Permissions
  • Increase Security by Editing the SSH Configuration File to allow Key-Based Authorization ONLY

Getting to Know Linux

I have recently undertaken to learn how to develop on the Linux platform. I grew up in the Windows world, and decided it was time to expand my horizons. After all, the vast bulk of the web runs on some variant of Linux, and some of today’s most in-demand web application development occurs in Ruby on Rails, which is most at home on a Linux machine.

What I have found so far is that there is a whole lot to like about this strange new OS, and the underlying philosophies and tools which form the core of the Linux experience.

One of the very first things I wanted to do was learn how to access a Linux box remotely from my Windows desktop. The first step in this process was understanding how to set up a Secure Shell (SSH) connection. At first it might seem this is a little redundant, since my Linux machine sits about 9 feet away from my Windows development box. However, this is a necessary first step in order to eventually be able to:

  • Spin up a Linux VM instance on a IAAS/cloud service such as Amazon EC2 and/or Windows Azure, and control/access/utilize it from my windows desktop.
  • Set up and manage a hosted Linux server for deployment of web applications/sites
  • Understand remote access in a Linux environment

Of course, on top of those items in the list above, this was also a good exercise to get me started doing useful things with my new Linux machine!

Minor Linux Familiarity Required

We will need to perform some Linux commands via the Bash Command Line Interface (CLI), both on our Linux machine, and through our remote connection once we get it set up. If, like myself, you are new to Linux, you may want to review some Bash basics. While the posts linked to below are parts of a series on using Git version control, each of the following focus on basic Bash commands used to navigate and manipulate files in a Linux system.

Review Basic Bash Navigation:

  • Getting Started with Git for the Windows Developer (Part II) – Get Acquainted with Bash
  • Getting Started with Git for the Windows Developer (Part III) – Working with Files Using Bash

Setting up the Linux Machine

I am using Linux Mint for my first forays into the Linux world. Mint is built atop Ubuntu, and features a friendly GUI for those of us just getting started. However, for me, the GUI is mainly for those “oh shit, I don’t know what to do” moments. One of my main purposes in setting up this machine was to utilize the Bash terminal as much as possible, and master this aspect of this new platform. In fact, we are going to perform this entire exercise using the Bash terminal when interacting with the Linux box.

For this post, I am dealing with a local Linux machine, on my home network behind a router. In another post, I will discuss exposing the machine to the outside world via the internet.

Installing OpenSSH on your Linux Machine

Having recently installed a fresh Mint OS, the first thing we have to do is install an SSH server. Your Linux Distro may or may not come pre-configured with OpenSSH, which I understand is the SSH server of choice in Linux-land.

Linux distro’s based on Debian-flavored Linux use the apt-get install newSotwareTitle to find and download software packages, and/or confirm and update existing installations if they are already present on your machine. So, let’s use apt-get to download OpenSSH on our Linux machine (note – this post assumes you have super-user/administrative permissions on your Linux machine):

Install OpenSSH:

Open the Bash terminal on your Linux machine, and type the following command and hit enter. Since you are using sudo to perform this action, be ready to enter your password prior to execution:

Install OpenSSH Server:
$ sudo apt-get install openssh-server

In my case, OpenSSH was already present on the system, so my terminal output looks like this:

install_openssh_server_thumb3

If your machine did not have OpenSSH Server installed, the terminal will ask that you confirm installation/update of any number of packages. Type “Y” and hit enter. You will then see the terminal window populate with the actions taken and packages added.

Now, we could do some of the SSH server configuration right now at our Bash terminal. However, instead, I am going to move over to the Windows side, and do the rest of the configuring from there, by way of an SSH connection.

The Most Common SSH Client for Windows – PuTTY (no, that is not a typo)

Use of the SSH protocol is less common in the Windows universe then in Linux. However, the most popular SSH client for use on a windows machine is PuTTY, an open source terminal emulator which can act as a client for SSH, Telnet, and other protocols. To get started setting up your SSH client on Windows, visit the PuTTY download page, download and install putty on your machine. The easiest way to go is to download the putty-0.62-installer.exe package, which includes everything required for our purposes:

  • Link to the PuTTY download site
  • Directly download the PuTTY installer

Once the download completes, run the installer.

Use PuTTYGen to Create a Public/Private key pair for your Windows client machine

SSH utilizes Key-based authorization to ensure the security of a connection. A simple description of how this works (From Wikipedia):

SSH uses public-key cryptography to authenticate the remote computer and allow it to authenticate the user, if necessary.[1] Anyone can produce a matching pair of different keys (public and private). The public key is placed on all computers that must allow access to the owner of the matching private key (the owner keeps the private key secret). While authentication is based on the private key, the key itself is never transferred through the network during authentication.

[Read More]

For our purposes, we will use the Handy PuTTYGen utility installed with our PuTTY package to create our keys. Open PuTTYGen (Start Menu –> PuTTY (Folder) –> PuTTYGen (application)) and you should see the following:

PuTTYGen, Ready to Create a Public/Private Key Pair:

PuTTY-Key-Generator-Before-Generate_

Leave the settings at their defaults, and click the “Generate” button. PuTTYGen will request that you move your cursor about in the large empty area in order to ad some “randomness” to the process (and in fact will pause generation until you DO):

PuTTY-Key-Generator-On-Generate_thum

When key generation is complete, you will be presented with some additional settings to complete before saving your keys:

PuTTY-Key-Generator-Comment--Passwor[2]

Complete the Following Items in the Generator Form as follows:

  • Key Comment can technically be anything you like, but convention is to use your email address
  • The Key Passphrase is not required, but is strongly recommended as an additional level of security, just in case anyone were to get hold of your private key. Use a reasonably strong (but easy to remember) pass word here.

Once you have completed these items, it is time to save your keys. First, I would create a directory (folder) in your Windows User Folder named “SSH Keys” in which to store your private keys. Then, click the “save private key” button and save the key there.

NOTE: Don’t use the “Save Public Key” feature. OpenSSH expects the public key in a slightly different format than PuTTYGen provides, so instead, we are going to copy the key as presented in the PuTTYGen window straight into our authorized_keys file once we log into our Linux machine.

ALSO NOTE: It is not necessary to save the public key which corresponds to the private key we just made, because we can use the PuTTYGen “Load” button to load our private key, which will then also load the proper public key data back into the Public Key Window for copying once again.

Leave the PuTTYGen Window open, and lets configure PuTTY for our first login.

Configure PuTTY for the Initial Login

The first time we log in to our Linux machine, we will use plain old password authentication, so that we can pass our public SSH key directly over the (relatively) secure connection, and avoid exposing it in a way which might result in someone else getting ahold of it. This is also good practice in a number of different ways.

Open the PuTTY application (Start Menu –> PuTTY (folder) –> PuTTY (application))

Enter the IP Address of your Linux Machine:

PuTTY-First-Login-Enter-Ip-Address_t

As you can see in the picture above, enter the IP Address of the Server machine (your Linux box). If you don’t know what the IP address of your Linux machine is, follow this link:

  • Find The IP Address of Your Computer on the Home or Local Area Network (LAN) -Linux (Debian-Based Systems)

Leave the port specification as the default value of 22 (this is the standard port used for SSH logins). While there are potential security reasons to change this later, for now it will do.

Next, in the tree menu to the left, select the Connection/Data node and enter your user name you use to log in to the Linux machine (REMINDER – we are assuming your user profile includes super-user permissions):

Enter your User Name in the Connection/Data node form:

PuTTY-Configuration-add-user-name_th

Leave the rest of the settings at their default values (as shown above). Now, go back to the Session node, and enter a name for this configuration in the “Saved Sessions” space, then click “Save. In my case, I saved this session configuration using the IP address, and a brief description of the configuration:

PuTTY-Configuration-Save-Pwd-Auth_th

First Remote Login to your Linux computer with Password Authentication

Ok, with those details tended to, click on the “open” button. This first time we log in, you will likely be presented with a warning dialog telling you that there are no keys cached for the server you are attempting to connect to, and do you wish to cache them now:

PuTTY-Security-Alert-Cahce-Server-Ad

Since we know this machine is on your LAN go ahead and click “Yes.” You should be presented with a terminal window that looks like this:

PuTTY-First-Login-Terminal-Enter-Use

Next, enter the password you use to log in to your Linux machine and hit enter (note that in the terminal here, the cursor does not move, nor are standard obfuscated password placeholders used – in other words, as you type your password, it will appear as if nothing is happening). Your terminal should now resemble this:

PuTTY-First-Login-Terminal-Logged-In[2]

Congratulations – you have now logged into your Linux terminal from your Windows computer. However, we are not yet using SSH, and in fact this method is not a very secure way to remotely access another machine. Next we need to set up our key-based authentication. Once we have confirmed all is well with that, we will disable the Username/Password-based authentication we are using now in favor of the much stronger key-based security.

Add Your Public Key to the Linux Machine

Your Linux system stores public SSH keys for client machines in a directory within your Linux home user folder (the .ssh directory), in the authorized_keys file. Your next step depends upon whether there is already an .ssh directory on your machine, and whether or not there is already an authorized_keys file present. We can find this out quickly enough by attempting to navigate into a directory named .ssh from within our home folder (our terminal should have opened within our home folder.

If you are not familiar with navigation and basic file manipulation in Bash (the Linux terminal), have a quick look at these two articles I wrote. The articles are part of a series on using Git, but these two focus on basic Bash shell commands useful for file and directory navigation:

  • Getting Started with Git for the Windows Developer (Part II) – Get Acquainted with Bash
  • Getting Started with Git for the Windows Developer (Part III) – Working with Files Using Bash

First, let’s attempt to navigate into the .ssh directory on our remote Linux box. Type the following into the terminal window (note – the “$’” symbol is not typed – this is the command “prompt” and indicates that the terminal is ready for command input):

$ cd .ssh

If there is not already a directory named .ssh in your user folder, your terminal window should look like this:

Navigate-to-ssh-directory-not-exists[2]

If this is the case, we need to create a new .ssh directory. Type the following:

$ mkdir .ssh

Now your terminal should look like this:

Create-ssh-Directory_thumb4

Now let’s try navigating into the new directory:

Navigate-to-new-ssh-directory_thumb2

That’s more like it! Next, since there was no .ssh directory to begin with, we also need to create our authorized keys file. We are going to create a new file, and add our new public key all in one fell swoop. Go to the PuTTYGen window (still open on your Windows desktop), and select and copy the entire public key visible in the space labeled “Public key for pasting into OpenSSH authorized_keys file”:

PuTTY-Key-Generator-Copy-Public-Key_

Now we will use the echo command to create the new authorized_keys file, and insert the Public key for our Windows machine. The syntax of our echo command is as follows:

echo YourPublicKey >> authorized_keys

This command will append YourPublicKey to the file authorized_keys. If the file does not exist, it will be created (ours doesn’t exist yet. If yours DOES, don’t do this this way).

First, type the echo command into the Linux remote terminal like this:

Type-Echo-Command-In-Terminal_thumb3

Then, if you right click your mouse pointer at the terminal cursor, the contents of your clipboard (containing your newly created public key for your Windows machine) will automatically paste into the current line.

Then add the >> authorized_keys to the end, and hit the Enter key:

Type-Append-to-authorized-keys-file_

Now that we have added our public key to the Linux machine, lets end our PuTTY session, and see if we can log back in using Public/Private key authentication. If this works, we will then modify our OpenSSH server configuration on the Linux box to ONLY allow this type of authorization. Go back to the Putty window, and close it. This will end the session.

Configure PuTTY for Public/Private Key Authorization

Now, open PuTTY again, and in the tree control to the left, load your previously saved session configuration, select the Connection/SSH/Auth node. Browse to find your private key you created using PuTTYGen, and select it for use. Leave the rest of the settings at their default values for now:

PuTTY-Configuration-Load-Private-Key[2]

Next, return to the Session configuration node, and type a new name for this modified configuration. As previously, I used the IP address, in conjunction with brief configuration details. Then click “Save”:

PuTTY-Configuration-Save-SSH-Auth_th

Connect to Linux/OpenSSH Server using Public/Private Key Authorization

Ok, let’s try connecting now, using our new configuration. Click on the Open button on the PuTTY interface. You should see something like this:

PuTTY-SSH-Login-Before-Enter-Passwor

Notice that this time, PuTTY tells us it is attempting to log in using public key authentication, and prompts us for the password we associated with our key when we created it. Enter the password you used when creating the key (again, the cursor will remain still while you do this), and hit Enter:

PuTTY-SSH-Logged-In_thumb2

Congratulations! You have now logged in to your Linux machine using Public/Private key authentication. While we are connected remotely, let’s tidy up a few loose ends.

Set Permissions on Keys File to Owner/Read-Only

Now that we know our keys are working properly, let’s protect the authorized_keys file on our Linux machine so that we don’t accidentally modify or delete it. Navigate into the .ssh directory, and type the following command into the Bash terminal:

chmod 400 authorized_keys

This sets the permissions on our authorized_keys file so that the current user, and only the current user has read-only permissions, and no one else can even access the file (that specific user can make the file writeable for themselves again by using chmod 700).

Set-KeyFile-Permissions_thumb3

Edit the OpenSSH Configuration File to Disable Password Authentication

Now that we have a working key-based authentication scheme, we have no more need for the less-then-secure password-only security we used previously. In fact, our next step will be to edit the OpenSSH configuration file on our Linux machine to NOT allow that, and to ONLY accept key-based authentication.

First, let’s make a backup copy of the configuration file. Type cd to navigate back to your home directory (entering cd with no options or destination path returns you to the home directory by default), then create a folder in your home directory to store backups like this:

$ mkdir ssh_config_backup

Then, use the following command to make a copy of the configuration file in the new directory we just created (note: Since we are using sudo, we will be prompted for the user password we use on the Linux machine):

$ sudo /etc/ssh/sshd_config ~/ssh_config_backup

Next, we will open the sshd_config file using vi in terminal mode. Type the following:

$ sudo vi /etc/ssh/sshd_config

Again, you will be promoted for your password on the Linux machine. You should see something like this after hitting the Enter key:

vi-On-File-Opened_thumb2

A few things to note:

  • I recognize it is difficult to see the dark blue text here. It will be easier to read on your actual screen
  • Notice that we are no longer in the Bash terminal per se, but instead looking at the text of the sshd_config file within the terminal.
  • At the moment, you cannot edit anything – vi is in command mode.

We will use a few (very few) basic vi commands to get this done. The Commands we need to edit this document are:

  • Use the up/down/left/right arrow keys to navigate within the document, and to position your cursor within a line of text.
  • If vi is in Command Mode, type i (lowercase i) to enter Insert mode.
  • If vi is in Insert mode, press the Esc key to return to Command Mode.
  • When you are finished editing, type :wq (colon then lowercase w the lowercase q) to save and exit the document, returning to the Bash Terminal proper.

Now, using your down arrow key, move down the document a ways until you find this line:

#PasswordAuthentication yes

We want to change it to:

PasswordAuthentication no

The hash symbol at the beginning of this line means that it has been “commented out” (meaning it is ignored when the OpenSSH server refers to this file during configuration). In addition, note its value is set to yes:

vi-Change-UsePasswordAuth_thumb2

First, type lowercase i to enter Insert mode, and delete the hash symbol. Then, use your right arrow key to move to the end of the line, and change the yes to no. Now press the Esc key to return to Command mode.

You would think this would be the end of it. However, at least in my current Linux Mint system, we also have to disable the Password Authentication Modules (PAM) portion of the config file (this is usually the last line in the file). To do this, use your down arrow key to navigate through the document until you find the following line:

UsePAM yes

We want to change it to:

UsePAM no

Your screen should look like this:vi-Change-UsePAM_thumb2

Use your Right-Arrow key to move to the end of that line, and type I to enter Insert Mode. Change the yes to no, then press the Esc key to return to Command Mode:

vi-Change-UsePAM-Set-To-No_thumb2

Now, once safely back in Command mode, type the following:

:wq

As you type, this command will appear at the bottom of the vi screen.

vi-Type-Colon-wq_thumb3

Once you hit enter, the modified file will be saved, and you will be returned to the Bash terminal:

vi-Return-To-Teminal-Window_thumb3

Restart the SSH Server

As a final step, we need to re-start the SSH Server on the Linux machine in order that the configuration changes we just made a reflected in the service. Type the following command into the terminal and hit enter:

$ sudo service ssh restart

Ok, now exit the current PuTTY session by closing the PuTTY window. Let’s see if we have succeeded in denying access for those seeking to login using simple password authentication. Re-open PuTTY, and load your original session configuration, which we set up without the key-based authentication using only our user name, and attempt to log in. If we have done everything correctly, you should be greeted with THIS unpleasant artifact:

Password-Login-Fails_thumb2

Hopefully, this has helped some of you get started using OpenSSH and PuTTY to connect to your Linux machine from a Windows box remotely. Of course, this is of limited usefulness when like me, your two machines are in the same room. In a future post I will discuss using SSH to connect to your Linux machine from the internet at large, and in conjunction with VNC to create a very secure Remote Desktop Connection.

Additionally, I began exploring this because my next goal is to utilize cloud services such as Amazon EC2 and Windows Azure. In that context, I want to be able to spin up a cloud-hosted Virtual Machine (VM) and perform this type of administrative stuff.

Please feel free to leave constructive feedback, and especially, to bust me where I have made a mistake or am propagating bad information. Comments are greatly appreciated!

В  мире ИТ существует уже довольно широкий спектр операционных систем, начиная с серверных, заканчивая операционными системами для мобильных устройств. В обычных пользовательских компьютерах и в серверах довольно часто используются две ОС — Linux и Windows. Поэтому очень часто возникают ситуации, когда приходится подключаться по сети из одной операционной системы к другой для выполнения разнообразных операций.

В этой статье мы рассмотрим варианты подключения к Linux из Windows. Существуют бесплатные и условно бесплатные утилиты вроде AnyDesk или TeamViewer, но установка их довольно тривиальна и не нуждается в дополнительном пояснении. Утилиты подобного рода обладают рядом ограничений при бесплатном некоммерческом использовании, либо их функциональность не удовлетворяет тем или иным потребностям пользователя. Мы рассмотрим полностью бесплатные способы как подключится к Linux из Windows.

Удалённый доступ к Linux с помощью VNC

На сегодняшний день самое популярное удаленное подключение к Linux из Windows, с использованием привычный в Windows графического интерфейса, является VNC (Virtual Network Computing) — утилита, использующая протокол RFB (Remote FrameBuffer — удалённый кадровый буфер). Управление осуществляется путём передачи нажатий клавиш на клавиатуре и движений мыши с одного компьютера на другой и ретрансляции содержимого экрана через компьютерную сеть.

В качестве сервера VNC в данном примере будет использоваться  TightVNC, установленный в Ubuntu 20.04. Для установки сервера VNC необходимо выполнить ряд действий:

Шаг 1. Установка рабочей среды XFCE

Xfce — одна из самых легковесных рабочих сред, используемых в Linux, она будет быстро работать даже при слабом и нестабильном сетевом подключении. Установите её с помощью команд:

sudo apt update

sudo apt install xfce4 xfce4-goodies

Шаг 2. Установка TightVNC

Далее установите TightVNC:

sudo apt install tightvncserver

Шаг 3. Настройка пароля

Перед началом выполнения всех действий необходимо задать пароль пользователя VNC.  Выполните команду:

vncpasswd

Вам будет предложено создать новый пароль, а также пароль только для просмотра. Откажитесь от второй опции:

Завершите процесс vncserver:

vncserver -kill :1

Шаг 4. Настройка скрипта запуска

Отредактируйте скрипт, который выполняется после запуска VNC-сервера:

nano ~/.vnc/xstartup

Он должен содержать такой текст:

#!/bin/sh
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
startxfce4 &

Сделайте файл исполняемым:

chmod +x ~/.vnc/xstartup

Шаг 5. Запуск VNC сервера

На этом этапе уже можно запустить VNC-сервер с помощью команды:

vncserver

Шаг 6. Подключение из Windows

Для того, чтобы подключиться из Windows к вашему Linux-серверу, используйте TightVNC Viewer.

Укажите IP-адрес компьютера, к которому нужно подключиться, и номер порта в поле Remote Host. В данном примере — 192.168.56.102::5901:

После того, как будет введён пароль, вы должны увидеть рабочий стол Xfce:

Шаг 8. Настройка systemd

Для того, чтобы запуск вашего VNC-сервера добавить в автозагрузку надо использовать systemd. Создайте новый файл сервиса systemd:

sudo nano /etc/systemd/system/vncserver@.service

Его содержимое должно быть следующим:

[Unit]
Description=Systemd VNC server startup script for Ubuntu 20.04
After=syslog.target network.target
[Service]
Type=forking
User=ubuntu
ExecStartPre=-/usr/bin/vncserver -kill :%i &> /dev/null
ExecStart=/usr/bin/vncserver -depth 24 -geometry 800x600 :%i
PIDFile=/home/ubuntu/.vnc/%H:%i.pid
ExecStop=/usr/bin/vncserver -kill :%i
[Install]
WantedBy=multi-user.target

Измените имя пользователя ubuntu и рабочего каталога ubuntu на нужные вам значения. Если у вас запущен VNC-сервер, остановите его:

vncserver -kill :1

Сообщите systemd о появлении нового сервиса:

sudo systemctl daemon-reload

Добавьте запуск вашего нового сервиса в список автозагрузки:

sudo systemctl enable vncserver@1.service

Запустите VNC-сервер:

sudo systemctl start vncserver@1

Использование RDP для удалённого подключения

Помимо VNC, для управления Linux-сервером из Windows можно воспользоваться RDP (Remote Desktop Protocol). Для этого на компьютере с Ubuntu 20.04 установите утилиту xrdp:

sudo apt install xrdp

Для корректной работы сервиса необходимо добавить пользователя xrdp в группу ssl-cert:

sudo adduser xrdp ssl-cert

Установите Xfce:

sudo apt-get install xfce4

Добавьте Xfce в сессии RDP в качестве рабочего стола по умолчанию:

echo xfce4-session >~/.xsession

Перезапустите сервис xrdp:

sudo systemctl restart xrdp.service

Процедура подключения из Windows к Linux-серверу по протоколу RDP почти ничем не отличается от подключения к удалённым Windows-серверам. Введите IP-адрес сервера, логин и пароль пользователя в Linux:

Если всё сделано правильно, вы увидите рабочий стол Xfce:

Для подключения к компьютеру под управлением Linux по протоколу SSH из Windows можно воспользоваться PowerShell. Сначала становите OpenSSH Client, если ещё не установлен. Запустите на вашем компьютере PowerShell от имени администратора системы и выполните следующую команду:

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

Это необходимо для того, чтобы узнать текущую версию SSH-клиента. В данном примере доступна версия OpenSSH.Client-0.0.1.0. Установите OpenSSH.Client с помощью команды:

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

Для того, чтобы подключиться к устройству, на котором запущен SSH-сервер, необходимо ввести имя пользователя и IP-адрес. Команда для подключения по SSH используя PowerShell выглядит так:

ssh ubuntu@192.168.56.1

Здесь ubuntu — имя пользователя на удалённом компьютере, а 192.168.56.1 — IP-адрес Linux-сервера, на котором запущен демон SSH.

При первом подключении необходимо подтвердить использование специального персонального ключа для шифрованного соединения по SSH-протоколу (введите слово Yes), затем введите пароль пользователя (в данном случае для пользователя ubuntu):

Как видите, соединение прошло успешно. Теперь можно выполнять все команды так же, как если бы вы их выполняли используя стандартный Linux SSH-клиент:

Для завершения терминальной сессии на удалённом компьютере введите команду exit. Теперь вы знаете как выполняется подключение к Linux из Windows по SSH.

Использование Putty для подключения к Linux

Пожалуй, одним из самых популярных способов подключения к Linux из Windows является кроссплатформенная утилита Putty — небольшая по размерам, но очень часто незаменима для подключения по таким протоколам как SSH, Telnet, rlogin и даже с помощью последовательных портов.

Для обычного подключения к Linux-серверу по протоколу SSH достаточно в поле Host Name (or IPaddress) указать его IP-адрес и нажать кнопку Open (в данном примере Linux-сервер имеет IP-адрес: 192.168.56.102):

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

Далее нужно будет ввести логин и пароль.  Если всё сделано правильно,  запустится удалённая сессия терминала Linux:

Мало кто знает, что Putty позволяет запустить почти любое приложение, установленное на компьютере с Linux, по сети в Windows. Для этого на компьютере с Windows нужно установить собственный X-сервер. В данном примере воспользуемся Xming.

Скачайте Xming с официального сайта. Установка довольно тривиальная, поэтому не будем на ней останавливаться. Ничего не меняйте в процессе установки. Просто нажимайте кнопку Next до тех пор, пока программа не установится и не запустится:

Когда установка Xming завершится, откройте Putty и в настройках сессии для вашего подключения в разделе SSH -> X11 включите флажок напротив опции Enable X11 forwarding, а также, в строке Отображение дисплея X впишите значение localhost:0, после чего откройте сессию подключения с помощью кнопки Open:

В открывшемся терминале Putty введите консольное название программы, обладающей графическим интерфейсом. В данном примере введено название графического редактора drawing:

drawing &

(Знак & позволит запустить программу в фоновом режиме, в этом случае в окне Putty можно будет выполнять и другие команды):

Как видите, Linux-приложение drawing успешно запустилось по сети на X-сервере, установленном в Windows. С ним можно работать так же, как и с локальным приложением.

Выводы

Сегодня не существует слишком уж больших проблем для подключения к Linux из Windows. Способов существует довольно много. Каждый из них обладает своими достоинствами и недостатками, например, скорость работы VNC, да и других тоже, существенно зависит от скорости сетевого соединения. Существуют также программные средства, позволяющие подключаться к Linux-серверам используя мессенджеры или браузеры.

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Creative Commons License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

  • Ssh connect to windows server
  • Ssh server windows 7 скачать
  • Ssh connect to host localhost port 22 connection refused windows
  • Ssh scp from linux to windows
  • Ssh no such file or directory windows