Как настроить значения тайм-аута SSH в CentOS / RHEL / Fedora |

Как настроить значения тайм-аута SSH в CentOS / RHEL / Fedora

Мануал

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

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

Конфигурация на стороне сервера

В файле /etc/ssh/sshd_config есть два параметра, связанных с бездействием ssh:
1. ClientAliveInterval
2. ClientAliveCountMax

Их значение можно найти, выполнив «man sshd_config», как показано ниже;

# man sshd_config
ClientAliveCountMax
        Sets the number of client alive messages (see below) which may be sent without sshd(8) receiving any mes-
        sages back from the client.  If this threshold is reached while client alive messages are being sent, sshd
        will disconnect the client, terminating the session.  It is important to note that the use of client alive
        messages is very different from TCPKeepAlive (below).  The client alive messages are sent through the
        encrypted channel and therefore will not be spoofable.  The TCP keepalive option enabled by TCPKeepAlive is
        spoofable.  The client alive mechanism is valuable when the client or server depend on knowing when a con-
        nection has become inactive.

        The default value is 3.  If ClientAliveInterval (see below) is set to 15, and ClientAliveCountMax is left at
        the default, unresponsive SSH clients will be disconnected after approximately 45 seconds.  This option
        applies to protocol version 2 only.

ClientAliveInterval
        Sets a timeout interval in seconds after which if no data has been received from the client, sshd(8) will
        send a message through the encrypted channel to request a response from the client.  The default is 0, indi-
        cating that these messages will not be sent to the client.  This option applies to protocol version 2 only.

Например, когда в конфигурационном файле sshd установлены следующие параметры, он завершит сеанс через 50 секунд (т. е. Когда ssh-сервер отправил 2 живых сообщения и ни один ответ не был получен от клиента ssh из-за проблем с сетью).

# vi /etc/ssh/sshd_config
ClientAliveInterval 25
ClientAliveCountMax 2

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

Это возможно, если для ClientAliveCountMax установить значение 0, а для ClientAliveInterval – желаемое время ожидания ввода пользователя до истечения времени ожидания сеанса пользователя.

В следующем примере представлена конфигурация, которую можно использовать для автоматического отключения сеанса пользователя ssh из-за отсутствия ввода в течение 2 минут:

# vi /etc/ssh/sshd_config
ClientAliveInterval 2m
ClientAliveCountMax 0

Конфигурация на стороне клиента

Клиент openssh имеет аналогичную пару значений конфигурации.

В файле /etc/ssh/ ssh_config есть два параметра, связанных с бездействием ssh:

1. ServerAliveInterval
2. ServerAliveCountMax

Их значение можно найти, выполнив команду man ssh_config, как показано ниже;

# man ssh_config
ServerAliveCountMax
        Sets the number of server alive messages (see below) which may be sent without ssh(1) receiving any messages
        back from the server.  If this threshold is reached while server alive messages are being sent, ssh will
        disconnect from the server, terminating the session.  It is important to note that the use of server alive
        messages is very different from TCPKeepAlive (below).  The server alive messages are sent through
        the encrypted channel and therefore will not be spoofable.  The TCP keepalive option enabled by 
        TCPKeepAlive is spoofable.  The server alive mechanism is valuable when the client or server depend 
        on knowing when a connection has become inactive.

        The default value is 3.  If, for example, ServerAliveInterval (see below) is set to 15 and 
        ServerAliveCountMax is left at the default, if the server becomes unresponsive, ssh will disconnect
        after approximately 45 seconds. 
        This option applies to protocol version 2 only.

ServerAliveInterval
        Sets a timeout interval in seconds after which if no data has been received from the server, ssh(1) 
        will send a message through the encrypted channel to request a response from the server.  
        The default is 0, indicating that these messages will not be sent to the server.  
        This option applies to protocol version 2 only.

Заключение

Параметры ClientAliveInterval и ClientAliveCountMax могут быть указаны только на сервере.

На стороне клиента есть аналог этих опций.

Если вы не можете изменить конфигурацию сервера SSH, используйте ServerAliveInterval и ServerAliveCountMax, чтобы инициировать трафик поддержки активности соединения с клиентского компьютера.

Эти параметры задаются в файле /etc/ssh/ssh_config, если их необходимо применять для всех пользователей на этом компьютере, или в ~/.ssh/config, если они применяются для отдельных пользователей.

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

По всей вероятности, серверу понадобится более короткий тайм-аут, поскольку он, вероятно, имеет дело с большим количеством соединений.

 

Пожалуйста, не спамьте и никого не оскорбляйте. Это поле для комментариев, а не спамбокс. Рекламные ссылки не индексируются!
Добавить комментарий