- Установка и настройка сервера SSH в Linux
- Установка пакетов SSH
- Настройка SSH
- Oracle linux ssh server
- Setting Up SSH on UNIX and Linux Systems
- To Set Up SSH on Oracle Solaris Systems
- To Set Up SSH on MacOS Systems
- To Set Up SSH on Linux systems
- Connecting to an Instance
- Required IAM Policy
- Prerequisites
- Connecting to a Linux Instance
- Connecting to a Windows Instance
- Prerequisites
- Making the Connection
- Connecting to an Instance on a Private Subnet Using a Bastion
- Troubleshooting the SSH Connection
Установка и настройка сервера SSH в Linux
Secure Shell, т. е. SSH – протокол, обеспечивающий защищённые соединения и передачу данных между двумя удалёнными компьютерами. Изначально создавался на замену таким системам как rlogin и rcp. Как понятно из полного названия протокола, система SSH позволяет соединяться и управлять удалённым узлом (компьютером, маршрутизатором и т. д.), при этом защищая весь передаваемый трафик с помощью высоконадёжного шифрования.
SSH широко применяется администраторами серверов для их настройки и управления, да и обычные продвинутые пользователи — владельцы, например, сайтов или виртуальных серверов активно используют SSH для подключения к своей учётной записи на хостинге и использования командной оболочки сервера.
Сразу после окончания разработки система SSH стала активно трансформироваться в закрытый коммерческий продукт в виде версии SSH2. Но благодаря сообществу GNU версии протокола SSH1 и SSH2 были реализованы в виде открытого и свободно распространяемого ПО openSSH. В Linux-системах используется именно этот метапакет.
Метапакет SSH базово включает в себя сервер SSH (sshd) в качестве програмы-демона, а также несколько утилит: ssh – удаленная регистрация и выполнение команд, scp – передача файлов и ssh-keygen – для генерации пар SSH-ключей.
Установка пакетов SSH
Как уже говорилось система ssh в Linux-системах распространяется в виде составного метапакета, поэтому для установки всех требуемых утилит ssh нужно выполнить всего одну команду:
В Ubuntu
После чего начнется процесс установки
Как видно, менеджер пакетов сам распознает все зависимые и связанные пакеты и установит их. Также, по завершению установки, автоматически будет запущен SSH-сервер в режиме демона. Это можно проверить командой:
$ systemctl status sshd
или:
$ service sshd status даст тот же вывод. Теперь сервер работает с базовыми настройками по-умолчанию.
Настройка SSH
Режим работы SSH-сервера с настройками по-умолчанию хоть и является вполне работоспособным для небольших частных сетей, всё же нуждается в задании некоторых важных параметров для использования на высоконадёжных публичных серверах. Настройки демона хранятся в файле /etc/ssh/sshd_config. Посмотреть его можно командой
В первую очередь следует обратить внимание на следующие параметры: Port, AddressFamily, ListenAddress. Первый глобально задаёт номер порта, через который будет работать соединение и если оставить его стандартным, т. е. 22, то велика вероятность, что он будет слишком часто сканироваться роботами.
Примечание: для задания активации параметра необходимо раскомментировать соответствующую строку — убрать символ «#» в её начале.
Второй параметр задаёт семейство используемых IP-адресов — IPv4 и IPv6. Если, к примеру, используются только адреса IPv4, то очень рекомендуется установить для параметра
Для адресов семейства IPv6 используется значение inet6.
Параметр ListenAddress позволяет задавать порты для отдельных сетевых интерфейсов:
Поскольку реализация openSSH позволяет работать с протоколами SSH1 и SSH2, то разумно отключить использование SSH1, т. к. эта версия является устаревшей. Работа по SSH1 крайне не рекомендуется: Protocol 2
Очень полезным является параметр, позволяющий проводить авторизацию и шифрование трафика с помощью специальных SSH-ключей:
Следует заметить, что в таком случае серверу необходимо явно указывать, где хранятся открытые ключи пользователей. Это может быть как один общий файл для хранения ключей всех пользователей (обычно это файл etc/.ssh/authorized_keys), так и отдельные для каждого пользователя ключи. Второй вариант предпочтительнее в силу удобства администрирования и повышения безопасности:
AuthorizedKeysFile etc/ssh/authorized_keys # Для общего файла
AuthorizedKeysFile %h/.ssh/authorized_keys # Файл -> пользователь
Во втором варианте благодаря шаблону автоподстановки с маской «%h» будет использоваться домашний каталог пользователя.
Важно также отключать парольный доступ:
Или же, в случае, если всё-таки необходимо использовать доступ по паролю, то обязательно нужно отключать авторизацию по пустому паролю:
Для указания разрешённых или запрещённых пользователей и групп служат директивы DenyUsers, AllowUsers, DenyGroups, и AllowGroups. Значениями для них являются списки имён, разделяемых пробелами, например:
Следует также отключать root-доступ:
Иногда, когда следует задавать мультисерверную конфигурацию, очень удобно использовать алиасы (Aliases), что позволяет настроить сразу несколько режимов доступа (с разными хостами, портами и т. д.) и использовать их, указывая при этом конкретный алиас:
Настройки для алиасов хранятся либо глобально в /etc/ssh/ssh_config, либо раздельно для пользователей в
/.ssh/config. Здесь нужно не спутать с ssh_config! Пример:
Для применения сделанных настроек необходим перезапуск SSH-сервера:
Настройка и использование клиента SSH
Для подключения по к серверу используется команда:
где user_name – имя пользователя в системе, host_name – имя узла, к которому производится подключение, например:
При этом утилита ssh запросит (в зависимости от настроек сервера) логин, пароль или парольную фразу для разблокировки приватного ключа пользователя.
В случае авторизации по ключу, должна быть предварительно сгенерирована пара SSH-ключей — открытый, который хранится на стороне сервера, обычно в файле .ssh/authorized_keys в домашнем каталоге пользователя, и закрытый — используется для авторизации клиента и хранится, как правило, в каталоге .ssh/ домашней директории пользователя. Открытый ключ представляет собой «цифровой слепок» закрытого ключа благодаря которому сервер «знает», кто «свой», а кто «чужой».
Для генерации ключей используется утилита ssh-keygen:
Утилита предложит выбрать расположение ключей (лучше всё оставить по-умолчанию), обычно это каталог
/.ssh/, ввести парольную фразу для закрытого ключа. После чего будут сгенерированы открытый ключ id_rsa.pub и закрытый — id_rsa. Теперь нужно скопировать открытый ключ, т. е. «слепок» закрытого на сервер. Проще всего этого можно добиться командой:
Теперь можно выполнить подключение командой ssh и запустить защищённый сеанс удалённого управления.
Важно заметить, что использование сгенерированных openSSH-ключей несовместимо с PPK-форматом, используемым по-умолчанию в таких комплексах как PuTTY. Поэтому необходимо конвертировать имеющиеся openSSH-ключи в формат PPK. Удобнее всего это делать с помощью утилиты PuTTY – puttygen.exe.
Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.
Источник
Oracle linux ssh server
Setting Up SSH on UNIX and Linux Systems
Setting up SSH on UNIX and Linux systems involves verifying that the SSH server daemon sshd is running and, if necessary, starting this daemon. Set up SSH on the DAS host and on all hosts where instances in your cluster will reside.
On UNIX and Linux systems, SSH software is typically installed as part of the base operating system. If SSH is not installed, download and install the appropriate OpenSSH SSH package for your operating system.
How to set up SSH on UNIX and Linux systems depends on the flavor of the operating system that you are running, as explained in the following sections:
To Set Up SSH on Oracle Solaris Systems
- Ensure that the following options in the configuration file /etc/ssh/sshd_config are set to yes:
If the daemon is running, no further action is required.
Example 2-2 Determining if the sshd Daemon Is Running on an Oracle Solaris System
This example confirms that the SSH server daemon sshd is running on an Oracle Solaris system.
After you have completed the setup of SSH on a host, test the setup on the host as explained in Testing the SSH Setup on a Host.
To Set Up SSH on MacOS Systems
- Open System Preferences and click Sharing.
The Sharing window opens.
The user that running the DAS or instance
After you have completed the setup of SSH on a host, test the setup on the host as explained in Testing the SSH Setup on a Host.
To Set Up SSH on Linux systems
- Ensure that the following options in the configuration file /etc/ssh/sshd_config are set to yes:
If the daemon is running, no further action is required.
Example 2-3 Determining if the sshd Daemon Is Running on a Linux System
This example confirms that the SSH server daemon sshd is running on a Linux system.
After you have completed the setup of SSH on a host, test the setup on the host as explained in Testing the SSH Setup on a Host.
Источник
Connecting to an Instance
You can connect to a running instance by using a Secure Shell (SSH)В or Remote Desktop connection. Most UNIX-style systems include an SSH client by default. Windows 10 and Windows Server 2019 systems should include the OpenSSH client, which you need if you created your instance using the SSH keys generated by Oracle Cloud Infrastructure . For other Windows versions, you can download a free SSH client called PuTTY from http://www.putty.org.
Note
If you created an instance without an SSH key, you can use the serial console to boot into maintenance mode and add or reset the SSH key for the opc user or reset the password for the opc user. Alternately, you can stop the instance, attach the boot volume to a new instance, and configure SSH on the new instance.
Required IAM Policy
To connect to a running instance with SSH, you don’t need an IAM policyВ to grant you access. However, to SSH you need the public IP address of the instance (see Prerequisites below). If there’s a policy that lets you launch an instance, that policy probably also lets you get the instance’s IP address. The simplest policy that does both is listed in Let users launch compute instances.
For administrators: Here’s a more restrictive policy that lets the specified group get the IP address of existing instances and use power actions on the instances (e.g., stop, start, etc.), but not launch or terminate instances. The policy assumes the instances and the cloud network are together in a single compartment (XYZ):
Prerequisites
You’ll need the following information to connect to the instance:
- The public IP address of the instance. You can get the address from the Instance Details page in the Console . Open the navigation menu and click Compute . Under Compute , click Instances. Then, select your instance. Alternatively, you can use the Core Services API ListVnicAttachments and GetVnic operations.
- The default username for the instance. If you used a platform image for Linux, CentOS, or Windows to launch the instance, the username is opc . If you used an Ubuntu platform image to launch the instance, the username is ubuntu .
- For Linux instances: The full path to the private key portion of the SSH keyВ pair that you used when you launched the instance. For more information about key pairs, see Managing Key Pairs on Linux Instances.
- For Windows instances: If you’re connecting to the instance for the first time, you will need the initial password for the instance. You can get the password from the Instance Details page in the Console .
Connecting to a Linux Instance
You connect to a Linux instance using SSH.
Use the following command to set the file permissions so that only you can read the file:
is the full path and name of the file that contains the private key associated with the instance you want to access.
Use the following SSHВ command to access the instance.
Note
Copy the following example to ensure the correct characters are used. If the wrong character is used in ssh -i , a Could not resolve hostname . No such host is known. error might occur.
is the full path and name of the file that contains the private key associated with the instance you want to access.
is the default username for the instance. For Oracle Linux and CentOS images, the default username is opc . For Ubuntu images, the default username is ubuntu .
is your instance IPВ address that you retrieved from the Console .
If the instance uses a key pair that was generated by Oracle Cloud Infrastructure , use the following procedure.
If this is the first time you are using this key pair, you must set the file permissions so that only you can read the file. Do the following:
- In Windows Explorer, navigate to the private key file, right-click the file, and then click Properties.
- On the Security tab, click Advanced.
- On the Permissions tab, for Permission entries, under Principal, ensure that your user account is listed.
- Click Disable Inheritance, and then select Convert inherited permissions into explicit permissions on this object.
- For Permission entries, select each permission entry that is not your user account and click Remove.
- Ensure that the access permission for your user account is Full control.
- Save your changes.
To connect to the instance, open Windows PowerShell and run the following command:
Note
Copy the following example to ensure the correct characters are used. If the wrong character is used in ssh -i , a Could not resolve hostname . No such host is known. error might occur.
is the full path and name of the file that contains the private key associated with the instance you want to access.
is the default username for the instance. For Oracle Linux and CentOS images, the default username is opc . For Ubuntu images, the default username is ubuntu .
is your instance IPВ address that you retrieved from the Console .
SSH private key files generated by Oracle Cloud Infrastructure are not compatible with PuTTY. If you are using a private key file generated during the instance creation process you need to convert the file to a .ppk file before you can use it with PuTTY to connect to the instance.
Note
If you changed the file permissions on your key to connect from a Windows system using OpenSSH, the key will not work with a PuTTY connection. Use OpenSSH to connect instead.
Convert a generated .key private key file:
Click Load, and select the private key generated when you created the instance. The extension for the key file is .key .
Click Save private key.
Specify a name for the key. The extension for new private key is .ppk .
Connect to the Linux instance using a .ppk private key file:
If the instance uses a key pair that you created using PuTTY Key Generator, use the following procedure.
In the Category pane, select Session and enter the following:
Host Name (or IP address):
is the default username for the instance. For Oracle Linux and CentOS images, the default username is opc . For Ubuntu images, the default username is ubuntu .
is your instance public IPВ address that you retrieved from the Console
Click Browse, and then select your .ppk private key file.
Click Open to start the session.
If this is your first time connecting to the instance, you might see a message that the server’s host key is not cached in the registry. Click Yes to continue the connection.
Tip
If the connection fails, you may need to update your PuTTY proxy configuration.
Connecting to a Windows Instance
You can connect to a Windows instance using a Remote Desktop connection. Most Windows systems include a Remote Desktop client by default.
Prerequisites
To use Remote Desktop Protocol (RDP) to access the Windows instance, you need to add a stateful ingress security rule for TCP traffic on destination port 3389 from source 0.0.0.0/0 and any source port. You can implement this security rule in either a network security group that the Windows instance belongs to or a security list that is used by the instance’s subnet.
- Open the navigation menu and click Compute . Under Compute , click Instances.
- Click the instance that you’re interested in.
- Under Instance details, for Virtual cloud network, click the name of the cloud network. The Virtual Cloud Network Details page opens.
To add the rule to a network security group that the instance belongs to:
- Under Resources, click Network Security Groups.
- Click the network security group that you’re interested in.
- Click Add Ingress Rules.
Enter the following values for the rule:
- Stateless: Leave the check box cleared.
- Direction: Leave Ingress selected.
- Source Type: CIDR
- Source CIDR: 0.0.0.0/0
- IPВ Protocol: RDP (TCP/3389)
- Source Port Range: All
- Destination Port Range: 3389
- Description: An optional description of the rule.
- Open the navigation menu and click Compute . Under Compute , click Instances.
- Click the instance that you’re interested in.
- Under Primary VNIC, for Subnet, click the name of the subnet. The Subnet Details page opens.
To add the rule to a security list that is used by the instance’s subnet:
- Under Resources, click Security Lists.
- Click the security list that you’re interested in.
- Click Add Ingress Rules.
Enter the following values for the rule:
- Stateless: Leave the check box cleared.
- Source Type: CIDR
- Source CIDR: 0.0.0.0/0
- IPВ Protocol: RDP (TCP/3389)
- Source Port Range: All
- Destination Port Range: 3389
- Description: An optional description of the rule.
Making the Connection
- Open the Remote Desktop client.
- In the Computer field, enter the public IP address of the instance. You can retrieve the public IP address from the Console .
- The User name is opc . Depending on the Remote Desktop client you are using, you might have to connect to the instance before you can enter this credential.
- Click Connect to start the session.
- Accept the certificate if you are prompted to do so.
If you are connecting to the instance for the first time, enter the initial password that was provided to you by Oracle Cloud Infrastructure when you launched the instance. You will be prompted to change the password as soon as you log in. Your new password must be at least 12 characters long and must comply with Microsoft’s password policy.
Otherwise, enter the password that you created. If you are using a custom image, you might need to know the password for the instance that the image was created from. For details about Windows custom images, see Creating Windows Custom Images.
Connecting to an Instance on a Private Subnet Using a Bastion
A subnet attached to an instance is either public or private. Instances on a private subnet can’t have public IP addresses. Oracle Cloud Infrastructure Bastion provides restricted and time-limited access to instances that don’t have public IP addresses.
Bastions let authorized users connect from specific IP addresses to instances using SSH sessions. When connected to a session, users can interact with the instance by using any software or protocol supported by SSH.
The Bastion service recognizes two types of sessions.
- Managed SSH sessions provide administrative access to the instance’s operating system. To connect to an instance using this session type the Bastion plugin must be enabled on the instance, and plugins must be running. For more information about how to enable and run plugins, see Managing Plugins with Oracle Cloud Agent.
- Port forwarding sessions (also known as SSH tunneling) create a secure connection between a specific port on the client machine and a specific port on the instance. Using this SSH connection you can relay other protocols like the Remote Desktop Protocol (RDP).
Troubleshooting the SSH Connection
If you’re unable to connect to your instance using SSH, follow these troubleshooting steps to identify common problems.
- Verify your connection: In your terminal window, run nc
If the SSH banner displays: You successfully connected to your instance using SSH. The underlying problem might be related to permissions. As a next step, verify your credentials. If the credentials you’re using to SSH to the instance are incorrect, the connection fails.
For Linux instances, you need the full path to the private key portion of the SSH keyВ pair that you used when you launched the instance. For more information about key pairs, see Managing Key Pairs on Linux Instances. For Windows instances, if you’re connecting to the instance for the first time, you need the initial password for the instance. You can get the password from the Instance Details page in the Console .
Capture serial console history: You can capture your instance’s serial console data history in the Console or by using the console-history resource in the CLI. This information can help determine the cause of connectivity problems. For more information about using the CLI, see console-history and Command Line Interface (CLI).
When using the CLI to capture the instance’s serial console data history, you need to include the following option to ensure that full history is captured. Without this option, the data might be truncated: —length 10000000 .
Источник