Перейти к содержимому

Как установить ssh на centos 7

  • автор:

How to Install / Enable OpenSSH on CentOS 7

Secure Shell (SSH) is a cryptographic protocol that allows a client to interact with a remote server in a secure environment.

High-level encryption protects the exchange of sensitive information and allows flie trans or issue commands on remote machines securely.

Learn how to enable SSH on CentOS 7 by following the instructions in this short tutorial.

Introduction image on how to enable or install SSH on CentOS 7

  • CentOS 7 system to act as an SSH server
  • A user with necessary permissions
  • Access to a command line (Ctrl-Alt-T)
  • yum utility (included by default)

Installing and Enabling OpenSSH on CentOS 7

SSH software packages are included on CentOS by default. However, if these packages are not present on your system, easily install them by completing Step 1, outlined below.

Step 1: Install OpenSSH Server Software Package

Enter the following command from your terminal to start the installation process:

sudo yum –y install openssh-server openssh-clients

This command installs both the OpenSSH client applications, as well as the OpenSSH server daemon, sshd.

verification latest client and server versions are installed

In this example, the system informs us that the latest version is already present.

Step 2: Starting SSH Service

To start the SSH daemon on the OpenSSH server:

sudo systemctl start sshd

When active, sshd continuously listens for client connections from any of the client tools. When a connection request occurs, sshd sets up the correct connection.

Step 3: Check sshd status

Check the status of the SSH daemon:

sudo systemctl status sshd

As we have previously started the service, the output confirms that it is active.

Check sshd status with systemctl command

To stop the SSH daemon enter:

systemctl stop sshd

We can check if the service has stopped by verifying the status. The output shows that the service is inactive and the time and date when the status last changed.

sshd is now inactive

Step 4: Enable OpenSSH Service

Enable SSH to start automatically after each system reboot by using the systemctl command:

sudo systemctl enable sshd

To disable SSH after reboot enter:

sudo systemctl disable sshd

OpenSSH Server Configuration

Properly configuring the sshd configuration file hardens server security. The most common settings to enhance security are changing the port number, disabling root logins, and limiting access to only certain users.

To edit these settings access the /etc/ssh/sshd_config file:

sudo vim /etc/ssh/sshd_config

Once you access the file by using a text editor (in this example we used vim), you can disable root logins and edit the default port number:

  • To disable root login:

PermitRootLogin no

  • Change the SSH port to run on a non-standard port. For example:

Port 2002

Settings in sshd config file of port 2002

Remember to uncomment the lines that you edit by removing the hashtag.

Save and close the file. Restart sshd:

service sshd restart

Note: We recommend you generate SSH keys for authentication, as a safer alternative to passwords.

Firewall Settings

After successfully enabling SSH and configuring the sshd file, adjust the firewall settings to make sure there are no compatibility issues.

It is also possible to restrict IP access to make the connection even more secure.

To restrict IP access, edit the iptables file by typing:

sudo vim /etc/sysconfig/iptables

To allow access using the port defined in the sshd config file, add the following line to the iptables file:

-A RH-Firewall-1-INPUT -m state --state NEW -m tcp -p tcp --dport 2002 -j ACCEPT

To restrict access to a specific IP, for example 133.123.40.166, edit the line as follows:

-A RH-Firewall-1-INPUT -s 133.123.40.166 -m state --state NEW -p tcp --dport 2002 -j ACCEPT

example of setting up firewall rules

If your site uses IPv6, and you are editing ip6tables, use the line:

-A RH-Firewall-1-INPUT -m tcp -p tcp --dport 2002 -j ACCEPT

Save and exit the file by pressing Escape (Esc) on your keyboard and typing:

:X

Press Enter to confirm.

Restart iptables to apply the changes:

sudo systemctl restart iptables

In this tutorial, we learned how to enable SSH on a CentOS 7 server. Additionally, we configured your firewall and SSH rules to limit access.

Your CentOS 7 server is now able to accept SSH connections.

Check out our guide on “ssh_exchange_identification: Read: Connection Reset By Peer” error if you notice it while connecting to your remote server.

Was this article helpful?
Vladimir Kaplarevic

Vladimir is a resident Tech Writer at phoenixNAP. He has more than 7 years of experience in implementing e-commerce and online payment solutions with various global IT services providers. His articles aim to instill a passion for innovative technologies in others by providing practical advice and using an engaging writing style.

Next you should read
August 25, 2019
Secure Shell is an important protocol for anyone managing and controlling remote machines.
July 30, 2019

If you are using Debian 9 or Debian 10 to manage servers, you must ensure that the transfer of data is safe.

June 14, 2019

Apache Tomcat is an open-source Java implementation package developed by the Apache Software Foundation.

April 29, 2019

In Linux, a repository is a central database of software. Most modern Linux distributions have a central repository.

Настройка SSH в CentOS: пошаговое руководство

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

Принцип работы SSH

SSH — это протокол, который создает зашифрованное соединение между пользовательским компьютером, устройством и сервером. Он позволяет осуществлять удаленный доступ и контроль над компьютером и включен по умолчанию в CentOS 7.

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

Многие хостинги предлагают своим клиентам за определенную плату SSH-подключение к домашнему каталогу. Это полезно для тех, кто предпочитает работать в командной строке, или для тех, кому необходимо удаленно запускать приложения, в том числе графические.

Настройка SSH в CentOS может отличаться в зависимости от ваших целей и задач. Однако можно выделить несколько общих моментов, на которые следует обратить внимание каждому пользователю. В том числе нужно ориентироваться на пользовательскую и серверную составляющие.

Этапы настройки SSH в CentOS

Рассмотрим основные этапы настройки и наиболее удобные способы.

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

  • Задайте в терминале соответствующую команду.

sudo yum -y install openssh-server openssh-clients

  • Введите пароль. Обратите внимание, что символы не будут отображаться.
  • Проверьте конфигурацию следующей командой.

sudo chkconfig sshd on

  • Запустите сервис. Для этого действия предусмотрена своя команда.

service sshd start

  • Убедитесь, что порт 22 работает.

netstat -tulpn | grep :22

Итак, подготовительные работы выполнены. Можно приступить к основной конфигурации.

Полезная рекомендация – внимательно читайте текст уведомлений в процессе использования команд. Они могут содержать предупреждения об ошибках. Если их игнорировать, есть риск столкнуться с проблемами в будущем.

  1. Редактирование конфигурационного файла

Рассмотрим процесс на примере редактора nano.

  • Установите его с помощью команды.

sudo yum install nano

  • Откройте конфигурационный файл.

sudo nano /etc/ssh/sshd_config

Вы увидите доступные параметры. Перед некоторыми из них есть символ решётки, это значит, что параметр закомментирован. Если решётку убрать, параметр будет активирован.

Для повышения уровня безопасности, добавьте ещё один протокол – «Protocol 2».

При желании можно изменить другие параметры, но это необязательно. Сохраните изменения, выбрав пункт «Записать» или нажмите на клавиатуре Ctrl + O.

Выйти из редактора тоже можно двумя способами: выбрав «выход» или нажав клавиши Ctrl + X.

  • Перезапустите сервис.

sudo service sshd restart

  • Проверьте, корректно ли он работает.

service sshd status

Алгоритм RSA используется в SSH для генерации пары ключей. Аббревиатура образована из имен Rivest, Shamir и Adleman. Этот процесс обеспечивает оптимальную защиту клиентской и серверной частей соединения. Чтобы получить доступ по SSH к серверу, необходимо сгенерировать соответствующий набор ключей SSH, состоящий из открытого и закрытого. То есть обязательно нужно создать пару ключей.

Чтобы это сделать, откройте командную строку на пользовательском компьютере. Введите команду.

В следующей строке можно задать путь для сохранения ключа. Если просто нажать Enter без изменений, останутся настройки по умолчанию.

Следующий этап – формирование пароля. В целях безопасности и избежания ошибок его нужно ввести 2 раза.

Ключ готов. Он представлен в виде графического изображения из символов. Например, такое.

  1. Копирование открытого ключа на сервер

Когда настроена аутентификация с помощью ключей SSH, нет необходимости каждый раз вводить пароль. Существует 3 способа копирования.

  • С помощью утилиты ssh-copy-id.

Это наиболее удобный способ. Но важно убедиться, что утилита уже установлена на компьютере. Введите следующую команду.

ssh-copy-id username@remote_host. В данном случае username@remote_host – это имя пользователя и хост удаленного сервера.

Машина выдаст оповещение и спросит, действительно ли вы собираетесь подключить сервер. Выбираем «yes» и вводим пароль. Всё готово.

  • Копирование ключа с помощью SSH

Напишите следующую команду. Не забудьте указать своё имя пользователя и хост вместо «username@remote_host».

cat ~/.ssh/id_rsa.pub | ssh username@remote_host «mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys»

Старые ключи останутся в файле, так как опция >> просто дописывают новую информацию без замены существующей. Введите пароль и перезагрузите сервер.

  • Копирование вручную.

Узнайте ключ с помощью команды.

Появится длинная комбинация символов, это и есть ключ. Скопируйте его и сохраните в отдельном файле.

Подключитесь к удалённому компьютеру, создайте каталог.

Введите ещё одну команду.

echo public_key_string >> ~/.ssh/authorized_keys

Так данные попадут в файл «authorized_keys». Найдите надпись «public_key_string». Вместо неё вставьте ключ, который скопировали ранее.

Готово. Теперь аутентификация к серверу будет происходить, если ввести «ssh username@remote_host».

How to Generate & Set Up SSH Keys on CentOS 7

Secure Shell (SSH) is an encrypted protocol used by Linux users to connect to their remote servers.

Generally, there are two ways for clients to access their servers – using password based authentication or public key based authentication.

Using SSH keys for authentication is highly recommended, as a safer alternative to passwords.

This tutorial will guide you through the steps on how to generate and set up SSH keys on CentOS 7. We also cover connecting to a remote server using the keys and disabling password authentication.

tutorial on generating SSH keys on CentOS 7

Before you start

1. Check for Existing Keys

Prior to any installation, it is wise to check whether there are any existing keys on the client machines.

Open the terminal and list all public keys stored with the following command:

ls -l ~/.ssh/id_*.pub

The output informs you about any generated keys currently on the system. If there aren’t any, the message tells you it cannot access /.ssh/id_*.pub , as there is no such file or directory.

no such directory or ssh key found

2. Verify SSH is Installed

To check if thw package is installed, run the command:

ssh -V

If you already have SSH, the output tells you which version it is running. Currently, the latest version is OpenSSH 8.0/8.0p1.

checking if ssh is installed screenshot

Note: Refer to our guide If you need to install and enable SSH on your CentOS system.

Steps to Creating SSH keys on CentOS

Step 1: Create SSH Key Pair

1. Start by logging into the source machine (local server) and creating a 2048-bit RSA key pair using the command:

ssh-keygen -t rsa

If you want to tighten up security measures, you can create a 4096-bit key by adding the -b 4096 flag:

ssh-keygen -t rsa -b 4096

2. After entering the command, you should see the following prompt:

Generating public/private rsa key pair. Enter file in which to save the key (home/your_username/.ssh/id_rsa): 

3. To save the file in the suggested directory, press Enter. Alternatively, you can specify another location.

Note: If you already have a key pair in the proposed location, it is advisable to pick another directory. Otherwise it will overwrite existing SSH keys.

4. Next, the prompt will continue with:

Enter passphrase (empty for no passphrase): Enter same passphrase again: 

Although creating a passphrase isn’t mandatory, it is highly advisable.

5. Finally, the output will end by specifying the following information:

Your identification has been saved in home/your_username/.ssh/id_rsa. Your public key has been saved in home/your_username/.ssh/id_rsa.pub. The key fingerprint is: KYg355:gKotTeU5NQ-5m296q55Ji57F8iO6c0K6GUr5:PO1iRk username@hostname The key's randomart image is: +------[RSA 3072]-------+ | .oo. | | +o+. | | + +.+ | | o + S . | | . E . . =.o| | . + . B+@o| | + . oo*=O| | oo . .+o+| | o=ooo=| +------ [SHA256] ------+

Now you need to add the public key to the remote CentOS server.

Step 2: Copy Public Key to CentOS Server

You can copy the public SSH key on the remote server using several different methods:

  1. using the ssh-copy-id script
  2. using Secure Copy (scp)
  3. manually copying the key

The fastest and easiest method is by utilizing ssh-copy-id . If the option is available, we recommend using it. Otherwise, try any of the other two noted.

Copy Public Key Using ssh-copy-id

1. Start by typing the following command, specifying the SSH user account, and the IP address of the remote host:

ssh-copy-id username@remote_host

If it is the first time your local computer is accessing this specific remote server you will receive the following output:

The authenticity of host '104.0.316.1 (104.0.316.1)' can't be established. ECDSA key fingerprint is KYg355:gKotTeU5NQ-5m296q55Ji57F8iO6c0K6GUr5:PO1iRk. Are you sure you want to continue connecting (yes/no)? yes

2. Confirm the connection – type yes and hit Enter.

3. Once it locates the id_rsa.pub key created on the local machine, it will ask you to provide the password for the remote account. Type in the password and hit Enter.

4. Once the connection has been established, it adds the public key on the remote server. This is done by copying the ~/.ssh/id_rsa.pub file to the remote server’s ~/.ssh directory. You can locate it under the name authorized_keys .

5. Lastly, the output tells you the number of keys added, along with clear instructions on what to do next:

Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'username@104.0.316.1'" and check to make sure that only the key(s) you wanted were added.
Copy Public Key Using Secure Copy

1. First, set up an SSH connection with the remote user:

ssh username@remote_host

2. Next, create the ~/.ssh directory as well as the authorized_keys file:

mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys

3. Use the chmod command to change the file permission:

chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys

chmod 700 makes the file executable, while chmod 600 allows the user to read and write the file.

4. Now, open a new terminal session, on the local computer.

5. Copy the content from id_rsa.pub (the SSH public key) to the previously created authorized_keys file on the remote CentOS server by typing the command:

scp ~/.ssh/id_rsa.pub username@remote_host:~/.ssh/authorized_keys

With this, the public key has been safely stored on the remote account.

Copy Public Key Manually

1. To manually add the public SSH key to the remote machine, you first need to open the content from the ~/.ssh/id_rsa.pub file:

cat ~/.ssh/id_rsa.pub

2. As in the image below, the key starts with ssh-rsa and ends with the username of the local computer and hostname of the remote machine:

example of a ssh public key on local machine username

3. Copy the content of the file, as you will need later.

4. Then, in the terminal window, connect to the remote server on which you wish to copy the public key. Use the following command to establish the connection:

ssh username@remote_host

5. Create a ~/.ssh directory and authorized_keys file on the CentOS server with the following command:

mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys

6. Change their file permission by typing:

chmod 700 ~/.ssh && chmod 600 ~/.ssh/authorized_keys

7. Next, open the authorized_keys file with an editor of your preference. For example, to open it with Nano, type:

nano authorized_keys

8. Add the public key, previously copied in step 2 of this section, in a new line in (under the existing content).

9. Save the changes and close the file.

10. Finally, log into the server to verify that everything is set up correctly.

Step 3: Connect to Remote Server Using SSH Keys

Once you have completed the previous steps (creating an RSA Key Pair and copying the Public Key to the CentOS server), you will be able to connect to the remote host without typing the password for the remote account.

All you need to do is type in the following command:

ssh username@remote_host

If you didn’t specify a passphrase while creating the SSH key pair, you will automatically log in the remote server.

Otherwise, type in the passphrase you supplied in the initial steps and press Enter.

Once the shell confirms the key match, it will open a new session for direct communication with the server.

Step 4: Disable Password Authentication

Although you managed to access the CentOS server without having to provide a password, it still has a password-based authentication system running on the machine. This makes it a potential target for brute force attacks.

You should disable password authentication entirely by following the outlined steps.

Note: Consider performing the following steps through a non-root account with sudo privileges, as an additional safety layer.

1. Using the SSH keys, log into the remote CentOS server which has administrative privileges:

ssh username@remote_host

2. Next, open the SSH daemon configuration file using a text editor of your choice:

sudo nano /etc/ssh/sshd_config

3. Look for the following line in the file:

PasswordAuthentication yes

4. Edit the configuration by changing the yes value to no . Thus, the directive should be as following:

PasswordAuthentication no

5. Save the file and exit the text editor.
6. To enable the changes, restart the sshd service using the command:

sudo systemctl restart sshd.service

7. Verify the SSH connection to the server is still functioning correctly. Open a new terminal window and type in the command:

ssh username@remote_host

In this article, you learned how to generate SSH key pairs and set up an SSH key-based authentication. We also covered copying keys to your remote CentOS server, and disabling SSH password authentication.

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

В этой статье мы расскажем, как пошагово происходит настройка SSH в CentOS.

SSH ― это протокол безопасного удаленного доступа, который позволяет пользователю управлять и вносить изменения на его удаленный сервер через интернет.

Чтобы получить доступ по SSH, нужно вводить пароль при каждом подключении к серверу. Это неудобно, если вы подключаетесь к серверу часто. Чтобы можно было входить в систему без пароля, на удаленном сервере должна быть настроена аутентификация (вход) с помощью ключей SSH.

Этап 1. Создание ключей

Для аутентификации на сервере нужно создать пару SSH-ключей — открытый и закрытый.

Создайте пару ключей:

ssh-keygen

Как настроить SSH на CentOS 1

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

Создайте надежный пароль для учетной записи:

Как настроить SSH на CentOS 3

На экране появится ключ и его изображение: CentOS install SSH

Готово, вы создали открытый и закрытый ключи. Теперь для входа в систему с помощью SSH-ключей нужно разместить открытый ключ на сервере и отключить аутентификацию (вход) по паролю.

Этап 2. Копирование открытого ключа на сервер

Копировать ключ на сервер можно двумя способами:

  • с помощью утилиты ssh-copy-id,
  • с помощью SSH.

Способ 1. Копирование открытого ключа с помощью утилиты ssh-copy-id

Копирование открытого ключа через утилиту ssh-copy-id ― самый быстрый и удобный способ. Введите утилиту:

ssh-copy-id username@IP
  • username — логин пользователя,
  • IP — IP-адрес сервера.

Как настроить SSH на CentOS 4

При первом соединении появится сообщение о том, что сервер является ненадежным источником. Для подключения введите в консоли yes и нажмите Enter:

Введите пароль от учетной записи и нажмите Enter.

Готово, вы скопировали открытый ключ на сервер.

Способ 2. Копирование открытого ключа с помощью SSH

Перед началом этих действий надо выполнить подключение по SSH обычным способом (через пароль) и произвести запуск удаленного соединения.

Введите команду:

cat ~/.ssh/id_rsa.pub | ssh username@remote_host "mkdir -p ~/.ssh && touch ~/.ssh/authorized_keys && chmod -R go= ~/.ssh && cat >> ~/.ssh/authorized_keys"

Как настроить SSH на CentOS 5

При первом соединении появится сообщение о том, что локальный компьютер не распознает хост. Для подключения введите в консоли yes и нажмите Enter: CentOS 7 SSH установка и настройка

Введите пароль от учётной записи и нажмите Enter.

Готово, вы скопировали открытый ключ на сервер.

Этап 3. Отключение аутентификации по паролю

Убедитесь, что вы настроили вход с помощью SSH-ключей для учетной записи root на сервере.
Откройте файл конфигурации демона SSH:

sudo nano /etc/ssh/sshd_config

Как настроить SSH на CentOS 6

Найдите в файле директиву PasswordAuthentication. Установите значение no:

Сохраните и закройте файл.
Перезапустите службу sshd:

sudo systemctl restart sshd.service

Готово, вы отключили вход по паролю.

Этап 4. Аутентификация на сервере

Если всё настроено верно, включить SSH-подключение можно без пароля с помощью команды:

ssh username@IP
  • username — логин пользователя,
  • IP — IP-адрес сервера.

Готово, теперь вы можете открыть SSH без пароля.

Помогла ли вам статья?

Спасибо за оценку. Рады помочь ��

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *