Различия
Здесь показаны различия между двумя версиями данной страницы.
Предыдущая версия справа и слева Предыдущая версия Следующая версия | Предыдущая версия | ||
wiki:руководство_по_ubuntu_server:удаленное_администрирование:openssh_server [2012/06/04 17:00] [Сервер OpenSSH] |
wiki:руководство_по_ubuntu_server:удаленное_администрирование:openssh_server [2012/12/23 13:19] [Ключи SSH] |
||
---|---|---|---|
Строка 8: | Строка 8: | ||
=====Сервер OpenSSH===== | =====Сервер OpenSSH===== | ||
- | ====Introduction==== | + | ====Введение==== |
- | This section of the Ubuntu Server Guide introduces a powerful collection of tools for the remote control of, and transfer of data between, networked computers called OpenSSH. You will also learn about some of the configuration settings possible with the OpenSSH server application and how to change them on your Ubuntu system. | + | Эта секция руководства по Ubuntu Server представляет мощную коллекцию инструментов для удаленного контроля и обмена данными с сетевыми компьютерами, названная OpenSSH. Вы также изучите некоторые конфигурационные настройки, доступные для серверного приложения OpenSSH, и то как изменять их на вашей Ubuntu системе. |
- | OpenSSH is a freely available version of the Secure Shell (SSH) protocol family of tools for remotely controlling, or transferring files between, computers. Traditional tools used to accomplish these functions, such as telnet or rcp, are insecure and transmit the user's password in cleartext when used. OpenSSH provides a server daemon and client tools to facilitate secure, encrypted remote control and file transfer operations, effectively replacing the legacy tools. | + | OpenSSH это свободно распространяемая версия семейства инструментов для удаленного управления компьютерами и передачи файлов с использованием протокола безопасной оболочки (SSH). Традиционные инструменты, используемые для этих функций, такие как telnet и rcp, незащищены и передают пользовательский пароль открытым текстом. OpenSSH предоставляет сервис на сервере и клиентские приложения для облегчения операций защиты, зашифрованного удаленного управления и передачи файлов, эффективно заменяя устаревшие инструменты. |
- | The OpenSSH server component, sshd, listens continuously for client connections from any of the client tools. When a connection request occurs, sshd sets up the correct connection depending on the type of client tool connecting. For example, if the remote computer is connecting with the ssh client application, the OpenSSH server sets up a remote control session after authentication. If a remote user connects to an OpenSSH server with scp, the OpenSSH server daemon initiates a secure copy of files between the server and client after authentication. OpenSSH can use many authentication methods, including plain password, public key, and Kerberos tickets. | + | Серверный компонент OpenSSH, sshd, постоянно ожидает клиентские подключения от любого клиентского приложения. Когда обнаруживается запрос на соединение, sshd устанавливает корректное соединение в зависимости от соединяющегося клиентского приложения. Например, если удаленный компьютер подсоединяется с помощью клиентского приложения ssh, сервер OpenSSH устанавливает сессию удаленного управления после авторизации. Если удаленный пользователь подсоединяется к серверу OpenSSH с помощью scp, сервис OpenSSH на сервере инициирует защищенное копирование файлов между сервером и клиентом после авторизации. OpenSSH может использовать много методов аутентификации, включая простой пароль, открытый ключ и билеты Kerberos. |
- | ====Installation==== | + | ====Установка==== |
- | Installation of the OpenSSH client and server applications is simple. To install the OpenSSH client applications on your Ubuntu system, use this command at a terminal prompt: | + | Установка клиента и сервера OpenSSH очень простая. Для установки клиентского приложения OpenSSH на вашей системе Ubuntu используйте команду в терминале: |
+ | <code>sudo apt-get install openssh-client</code> | ||
- | sudo apt-get install openssh-client | + | Для установки серверного приложения OpenSSH и связанных файлов используйте такую команду в терминале: |
+ | <code>sudo apt-get install openssh-server</code> | ||
- | To install the OpenSSH server application, and related support files, use this command at a terminal prompt: | + | Пакет openssh-server может быть выбран для установки во время процесса установки Ubuntu Server Edition. |
- | sudo apt-get install openssh-server | + | ====Конфигурация==== |
- | The openssh-server package can also be selected to install during the Server Edition installation process. | + | Вы можете настроить поведение по умолчанию серверного приложения OpenSSH, sshd, редактируя файл /etc/ssh/sshd_config. Для информации по конфигурационным директивам, используемым в этом файле, вы можете посмотреть соответствующую страницу руководства, задав следующую команду в терминале: |
+ | <code>man sshd_config</code> | ||
- | ====Configuration==== | + | Существует множество директив в конфигурационном файле sshd, управляющих такими вещами, как настройки соединений и способы авторизации. Далее примеры конфигурационных директив, которые могут быть изменены редактированием файла /etc/ssh/sshd_config. |
- | You may configure the default behavior of the OpenSSH server application, sshd, by editing the file /etc/ssh/sshd_config. For information about the configuration directives used in this file, you may view the appropriate manual page with the following command, issued at a terminal prompt: | + | <note tip>Прежде, чем редактировать конфигурационный файл, стоит создать копию оригинального файла и защитить его от записи, чтобы у вас были оригинальные настройки как справочник, который можно использовать повторно при необходимости. |
- | man sshd_config | + | Скопируйте файл /etc/ssh/sshd_config и защитите его от записи с помощью следующих команд в терминале: |
+ | <code>sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original | ||
+ | sudo chmod a-w /etc/ssh/sshd_config.original</code></note> | ||
- | There are many directives in the sshd configuration file controlling such things as communication settings, and authentication modes. The following are examples of configuration directives that can be changed by editing the /etc/ssh/sshd_config file. | + | Далее примеры конфигурационных директив, которые вы можете изменить: |
- | Prior to editing the configuration file, you should make a copy of the original file and protect it from writing so you will have the original settings as a reference and to reuse as necessary. | + | ** Чтобы установить TCP порт прослушивания для вашего OpenSSH 2222 вместо стандартного 22, измените директиву **Port** таким образом: |
+ | <code>Port 2222</code> | ||
+ | ** Чтобы sshd допускал вход с использованием открытых ключей, просто добавьте или измените строку: | ||
+ | <code>PubkeyAuthentication yes</code> | ||
+ | Если строка уже присутствует, убедитесь, что она не закомментирована. | ||
+ | ** Чтобы позволить вашему OpenSSH серверу показывать содержимое файла /etc/issue.net в качестве шапки пред авторизацией, просто добавьте или измените строку: | ||
+ | <code>Banner /etc/issue.net</code> | ||
- | Copy the /etc/ssh/sshd_config file and protect it from writing with the following commands, issued at a terminal prompt: | + | Все изменения производятся в файле /etc/ssh/sshd_config. |
- | sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.original | + | После изменений в /etc/ssh/sshd_config, сохраните файл и перестартуйте серверное приложение sshd для применения изменний, используя команду в терминале: |
- | sudo chmod a-w /etc/ssh/sshd_config.original | + | <code>sudo /etc/init.d/ssh restart</code> |
- | The following are examples of configuration directives you may change: | + | <note important>Множество других директив конфигурации sshd доступны для изменения поведения серверного приложения под ваши нужды. Однако учтите, что если единственный способ доступа к серверу - это ssh и вы допустили ошибку конфигурации sshd в /etc/ssh/sshd_config, вы можете найти свой сервер заблокированным, пока его не перезагрузите. В дополнение, если неправильная директива настройки воспринялась, сервер sshd может отказаться загружаться, поэтому будьте очень осторожны, когда редактируете этот файл на удаленном сервере. |
+ | </note> | ||
- | To set your OpenSSH to listen on TCP port 2222 instead of the default TCP port 22, change the Port directive as such: | + | ====Ключи SSH==== |
- | Port 2222 | + | Ключи SSH разрешают авторизацию между двумя узлами без необходимости ввода пароля. Авторизация по ключам SSH использует два ключа: секретный и открытый. |
- | To have sshd allow public key-based login credentials, simply add or modify the line: | + | Для создания ключей введите в терминале клиента: |
+ | <code>ssh-keygen -t dsa</code> | ||
- | PubkeyAuthentication yes | + | Это сгенерирует ключи использующие метод цифрового алгоритма подписи (DSA). В процессе у вас спросят пароль. Просто нажмите Enter на запрос о создании ключа. |
+ | По умолчанию открытый ключ сохраняется в файл ~/.ssh/id_dsa.pub, в то время как секретный в ~/.ssh/id_dsa. Теперь скопируйте файл id_dsa.pub на удаленный компьютер и добавьте его к ~/.ssh/authorized_keys командой: | ||
+ | <code>ssh-copy-id username@remotehost</code> | ||
- | If the line is already present, then ensure it is not commented out. | + | В конце дважды проверьте права доступа файла authorized_keys, чтобы только авторизованные пользователи имели права на чтение и запись. Если права установлены некорректно, измените их: |
+ | <code>chmod 600 .ssh/authorized_keys</code> | ||
- | To make your OpenSSH server display the contents of the /etc/issue.net file as a pre-login banner, simply add or modify the line: | + | Теперь у вас есть возможность соединиться по SSH с этим узлом без ввода пароля. |
- | Banner /etc/issue.net | + | ====Ссылки==== |
- | In the /etc/ssh/sshd_config file. | + | -- Страница [[https://help.ubuntu.com/community/SSH|SSH на wiki Ubuntu]] |
- | + | -- [[http://www.openssh.org/|Сайт OpenSSH]] | |
- | After making changes to the /etc/ssh/sshd_config file, save the file, and restart the sshd server application to effect the changes using the following command at a terminal prompt: | + | -- Страница [[https://wiki.ubuntu.com/AdvancedOpenSSH|продвинутого OpenSSH на wiki]] |
- | + | ||
- | sudo /etc/init.d/ssh restart | + | |
- | + | ||
- | Many other configuration directives for sshd are available to change the server application's behavior to fit your needs. Be advised, however, if your only method of access to a server is ssh, and you make a mistake in configuring sshd via the /etc/ssh/sshd_config file, you may find you are locked out of the server upon restarting it. Additionally, if an incorrect configuration directive is supplied, the sshd server may refuse to start, so be extra careful when editing this file on a remote server. | + | |
- | + | ||
- | ====SSH Keys==== | + | |
- | + | ||
- | SSH keys allow authentication between two hosts without the need of a password. SSH key authentication uses two keys, a private key and a public key. | + | |
- | + | ||
- | To generate the keys, from a terminal prompt enter: | + | |
- | + | ||
- | ssh-keygen -t dsa | + | |
- | + | ||
- | This will generate the keys using the Digital Signature Algorithm (DSA) method. During the process you will be prompted for a password. Simply hit Enter when prompted to create the key. | + | |
- | + | ||
- | By default the public key is saved in the file ~/.ssh/id_dsa.pub, while ~/.ssh/id_dsa is the private key. Now copy the id_dsa.pub file to the remote host and append it to ~/.ssh/authorized_keys by entering: | + | |
- | + | ||
- | ssh-copy-id username@remotehost | + | |
- | + | ||
- | Finally, double check the permissions on the authorized_keys file, only the authenticated user should have read and write permissions. If the permissions are not correct change them by: | + | |
- | + | ||
- | chmod 600 .ssh/authorized_keys | + | |
- | + | ||
- | You should now be able to SSH to the host without being prompted for a password. | + | |
- | + | ||
- | ====References==== | + | |
- | + | ||
- | Ubuntu Wiki SSH page. | + | |
- | + | ||
- | OpenSSH Website | + | |
- | + | ||
- | Advanced OpenSSH Wiki Page | + | |
---- | ---- |