Ssh to linux desktop

Установка SSH в Ubuntu

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

Служба SSH позволяет получить доступ к терминалу удаленного компьютера и выполнить там все необходимые вам команды. При своей простоте она достаточно безопасна, чтобы использоваться для решения серьезных коммерческих задач, так и задач обычных пользователей. В этой статье мы рассмотрим как выполняется установка SSH в Ubuntu 20.04, а также поговорим о начальной настройке SSH сервера.

Что такое SSH?

SSH или Secure Shell — это протокол безопасного доступа из одного компьютера к другому по сети. У протокола SSH очень много возможностей. Вы можете создавать защищенные соединения между компьютерами, открывать командную строку на удаленном компьютере, запускать графические программы, передавать файлы и организовывать частные сети.

За поддержку протокола SSH в Linux отвечает набор программного обеспечения OpenSSH. Это открытая реализация этого протокола, которая предоставляет все необходимые возможности. В состав пакета OpenSSH входят утилиты для установки соединения, передачи файлов, а также сам ssh сервер.

Установка OpenSSH в Ubuntu

Установить SSH на Ubuntu будет очень просто, программа считается стандартной и используется почти везде. Хотя по умолчанию в дистрибутиве её нет, но зато она есть в официальных репозиториях.

Поэтому для установки откройте терминал с помощью сочетания клавиш Ctrl+Alt+T и выполните команду:

sudo apt install openssh-server

ssh

Будет загружено несколько пакетов, а когда установка ssh сервера Ubuntu завершится, программа будет готова к работе. Если вы хотите чтобы служба запускалась автоматически нужно добавить его в автозагрузку. Поэтому чтобы включить SSH в Ubuntu 20.04 выполните:

sudo systemctl enable sshd

ssh1

Если затем вы захотите удалить службу из автозагрузки, используйте команду disable:

sudo systemctl disable sshd

Что касается клиента ssh, то он уже установлен в системе по умолчанию. Сейчас вы можете попробовать подключиться к локальному ssh серверу просто набрав:

ssh3

В одной из предыдущих статей мы рассматривали что означает адрес 0.0.0.0, сейчас вы можете убедиться что в пределах этой машины он значит локальный адрес:

ssh2

Точно таким способом вы можете получить ssh доступ ubuntu к любому другому компьютеру из сети. Для этого достаточно указать вместо localhost его ip адрес и имя пользователя в таком формате:

Читайте также:  Dll libraries in linux

$ ssh имя_пользователя @ ip_адрес

Настройка SSH в Ubuntu

С параметрами по умолчанию сервер SSH не очень безопасен поэтому перед тем, как программа будет готова к полноценному использованию ее нужно немного настроить. Все настройки сервера SSH хранятся в конфигурационном файле sshd_config, который находится в папке /etc/ssh.

Перед тем как вносить изменения в этот конфигурационный файл рекомендуется сделать его резервную копию, для этого можете использовать такую команду:

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.factory-defaults

Дальше вы можете перейти к настройке конфигурационного файла:

sudo vi /etc/ssh/sshd_config

Первым делом желательно сменить порт, на котором работает ssh, возможный злоумышленник не знал включен ли у вас этот сервис. Найдите в конфигурационном файле строчку Port и замените ее значение на любое число, например, Port 2222:

ssh4

По умолчанию вход от имени суперпользователя включен, рекомендуется отключить такую возможность. Для этого найдите строчку PermitRootLogin и замените ее значение на no:

ssh5

Чтобы разрешить аутентификацию по ключу, а не по паролю найдите строку PubkeyAuthentication и убедитесь, что ее значение yes.

ssh6

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

sudo systemctl restart ssh

Более подробно про настройку и использование различных тонкостей ssh рассказано в статье как использовать ssh.

Если вы изменили порт, то при подключении в клиенте тоже нужно указать новый порт, так как по умолчанию будет использоваться 22, например:

К тому же, если на компьютере установлен и настроен брандмауэр, то в нем тоже нужно разрешить доступ к новому порту ssh, для этого выполните:

Даже если служба ssh находится на порту по умолчанию, его тоже нужно открыть в брандмауэре если вы собираетесь подключаться к компьютеру через интернет:

Настройка ssh Ubuntu 20.04 полностью завершена.

Выводы

Теперь, когда установка SSH в Ubuntu 20.04 завершена, вы можете получить удаленный доступ к своему компьютеру через интернет и быть уверенными что он находится в безопасности. Если у вас остались вопросы, спрашивайте в комментариях.

На завершение видео, где подробно рассказано о том, что такое SSH:

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

Источник

How to install and use SSH on Linux

For example, I use SSH to connect to my virtual private server and to my office computer. Usually, it works only through the terminal. However, you can connect it to your file manager or use some graphical programs like FileZilla, if you do not want to type commands. You can also use graphical forwarding and open graphical programs from the remote server in your local computer.

SSH is a simple, reliable, and very secure way to establish a connection between computers. In this post, you will learn how to install, configure, and use SSH on Linux. In particular, I will show how to:

Читайте также:  Arch linux grub install efi

Configure SSH on a Local Computer

First, you need to set up your client Linux machine. This is the computer you will use to connect from.

You need to install openssh-client on your Linux computer.

sudo apt install openssh-client 
sudo zypper install openssh 
sudo dnf install -y openssh-clients 

If you also need to use Windows as a client install PuTTY.

Configure SSH on a Remote Computer

Next, configure the computer you want to connect to.

Install SSH server

On the remote computer, you need to install openssh-server .

sudo apt install openssh-server 
sudo pacman -S openssh sudo systemctl enable sshd sudo systemctl start sshd 
sudo dnf install -y openssh-server sudo systemctl enable sshd sudo systemctl start sshd 
sudo zypper install openssh sudo systemctl enable sshd sudo systemctl start sshd 

Obviously, you will need to have physical access to the remote computer to install this package. For example, if it is my office computer, I will go to my office and install this openssh-server program.

Check SSH status

After the installation, check that SSH is running with:

sudo systemctl status ssh 

You should see that it is active:

SSH server service is active

If it has not started, start it manually:

or simply reboot the system.

Find out Server’s IP

Next, you need to determine the IP address of this remote computer.

The easiest way is to check the network settings. If you have a graphical desktop in that computer, open the network settings and search for IP address.

This is how it looks in Plasma 5:

Plasma5 NetworkSettings IP address

GNOME NetworkSettings IP address

If you only have the command line, run:

Usually, you will see your IP address in the eth0 connection.

output of the command: ip a

Write down this address, you will need it to be able to connect to this remote computer.

Open SSH port in Firewall

It is possible that you use a firewall and it may block your remote access. So, check open ports:

sudo lsof -i -P -n | grep LISTEN 

You should see that port 22 is open. If you do not find port 22 open among open ports, go to your firewall settings and open it.

the command to check open ports in Linux

If you use UFW run this command:

I discuss whether you need a firewall in Linux and how to use it in this post.

Connect using SSH

Now, I assume your remote computer is configured and you are sitting in front of your client Linux machine.

In your client Linux computer, run:

ssh remoteuser@remote-ip-address 

You use the username of the remote computer and the IP address is the address you wrote down in a previous step.

If you get a warning “Are you sure you want to continue connecting (yes/no)?”, type yes.

After you typed the password of your user at the remote computer, you will be logged in to a remote Linux computer.

Читайте также:  Linux bash shell on windows 10

first SSH log in

Now, you can work on this remote computer as if you would be sitting in front of that computer and using the terminal.

SSH in FileZilla

If you simply want to work with files without running any programs, you can also connect to your remote server with FileZilla.

In FileZilla, go to the Site manager and add a new site with SFTP protocol:

FileZilla SSH connection settings

You will get your local files on the left and your remote files on the right.

FileZilla SSH file transfer

You can navigate in FileZilla with your mouse and transfer files between your computers by simple drag-and-drop between these two panels.

SSH in File Manager

Similarly, you can add the remote server to your File Manager. I use Dolphin file manager of Plasma 5 but the procedure is very similar in other file managers.

Go to the Network in your file manager and add a Network folder:

Dolphin SSH connection settings

Among these options, select SFTP protocol, give a name to this folder, provide the user name of the remote account, IP address of the remote computer. In the field “remote folder path”, you can use your remote user home folder or any other folder you want to connect to.

Dolphin SSH folder

As a result, you will see all the folders and files of your remote computer in your file manager.

Forward X

You can also forward graphical application from your remote computer to your local computer. To do that, you simply need to add the option -X during the login.

ssh -X remoteuser@remote-ip-address 

Now, if you start any graphical program in a remote computer, it will open in your local computer, like this Firefox on the screenshot.

SSH Forward X

Transfer files

To transfer a file to a remote computer in the terminal run:

scp /path/to/local/file remoteuser@remote-ip-address:/path/to/remote/file 

And to transfer a file from a remote computer to your local computer simply type first the remote address and then local.

scp remoteuser@remote-ip-address:/path/to/remote/file /path/to/local/file 

You can also use wild cards to transfer many files at the same time. I showed how to use wild cards in this YouTube video.

Final thoughts

As you have seen SSH is a pretty handy program. It is not difficult to install and use. There are some more configurations you do to your SSH. I recommend enhancing the security of your SSH connection with SSH keys and white-listed IP addresses.

Average Linux UserFollow I am the founder of the Average Linux User project, which is a hobby I work on at night. During the day I am a scientist who uses computers to analyze genetic data.

Источник

Оцените статью
Adblock
detector