Linux ssh session timeout

How to set ssh timeout?

I’m executing a script connecting via password-less SSH on a remote host. I want to set a timeout, so that if the remote host is taking an infinite time to run, I want to come out of that ssh session and continue other lines in my sh script. How can I set a timeout?

This should probably be closed to be in line with the closing of a complete duplicate of this how to decrease ssh connection timeout value [closed]

If you redirected here only to «stay more time in your ssh session» (question «How to increase SSH Connection timeout?»), this is the wrong place. The answer is at this link about ssh-timeout.

8 Answers 8

Where 10 is time in seconds. This Timeout applies only to the creation of the connection.

This doesn’t actually work for «the remote host is taking an infinite time to run»: «ssh -o ConnectTimeout=5 host ‘sleep 10′» waits for 10 seconds, not 5.

@FerryBoender It seems obvious that ConnectTimeout affects only the connection. Your example connects with success.

Use the -o ConnectTimeout and -o BatchMode=yes -o StrictHostKeyChecking=no .

ConnectTimeout keeps the script from hanging, BatchMode keeps it from hanging with Host unknown, YES to add to known_hosts, and StrictHostKeyChecking adds the fingerprint automatically.

**** NOTE **** The «StrictHostKeyChecking» was only intended for internal networks where you trust you hosts. Depending on the version of the SSH client, the «Are you sure you want to add your fingerprint» can cause the client to hang indefinitely (mainly old versions running on AIX). Most modern versions do not suffer from this issue. If you have to deal with fingerprints with multiple hosts, I recommend maintaining the known_hosts file with some sort of configuration management tool like puppet/ansible/chef/salt/etc.

Not only does -o StrictHostKeyChecking=no not address the question, but it’s a terrible idea if you care about security, which might be the reason you’re using SSH in the first place.

It is good to point out the possible security implications of -o StrictHostKeyChecking=no. However, it will prevent the script from hanging during execution.

WARNING. As @Dolph wrote, do NOT use StrictHostKeyChecking=no if you care about security at all. @Doug: script will not hang — it will just insist that you ssh to remote host manually the first time, so it gets to know the host. But it will protect you against MITM attacks. Please edit this answer to reflect this as it is a very dangerous advice as it stands. And it wasn’t even asked for.

Читайте также:  Linux права файл командная строка

Источник

How to Keeping SSH Session Alive in Linux

SSH or Secure Shell is an invaluable utility when it comes to undertaking remote login objectives on remote machines. For Linux users, the SSH utility offers more than just remote login solutions.

The mentioned users are also able to effortlessly accomplish Linux administrative tasks. Regardless of whether the targeted remote machine is untrustworthy or whether the network that facilitates the communication between the two machines is insecure, SSH ensures that these communications are secure and encrypted.

It is sometimes frustrating when an SSH session ends too soon while we are multitasking on the Linux terminal environment. Finding a way of keeping the SSH session alive for as long as possible can be a game changer for Linux users who don’t want to keep on re-initiating new SSH sessions.

This article will walk us through the needed steps that will help us keep any SSH session alive as long as possible until we manually decide to close the Linux terminal window.

Prerequisites

  • Have openssh-client installed on the Linux system initiating the SSH connection (client machine).
  • Have openssh-server installed on the remote Linux system receiving the initiated SSH connection (server machine).

Why SSH Sessions End

Usually, it is the ssh daemon running on the server machine that makes it possible for an ssh connection from the client machine to be possible. If the SSH connection is successful and the server and client machines do not periodically communicate, the server machine closes the connection after some fixed grace period.

To address this issue, we have made some configuration changes on an SSH config file on either the server or client machine.

When SSH Connection is Coming from the Client Machine

On the client machine, the SSH config file should be located at $HOME/.ssh/config. If it does not exist, we will need to create it.

$ cat $HOME/.ssh/config OR $ touch $HOME/.ssh/config

Use the chmod command to reserve the read and write privileges of this file only to the current user and no other user. In short, we are keeping this file access private.

Let us now open and add some ssh rules to this file, you can use a text editor of your choice if needed.

Add the following lines in the file before saving and closing it.

Host * ServerAliveInterval 300

Keep SSH Connection Alive

If your SSH connection is tied to a specific host, you could edit the above file entry to look like the following:

Host my_hostname.com ServerAliveInterval 300

From the above demonstration, the client machine will wait for 300 seconds before allowing the server machine to close the ssh connection.

When SSH Connection is Coming from the Server Machine

You might also find yourself in circumstances where you need to use your server machine or a remote machine to access a client.

Читайте также:  Как linux запустить apk

On the server machine, access and open the file /etc/ssh/sshd_config or /etc/ssh/ssh_config as its naming convention sometimes depends on the Linux OS distribution in use.

$ sudo nano /etc/ssh/ssh_config

Since we are after an ssh connection to a client machine, add the following key value at the bottom of the file:

Set SSH Connection Timeout

This value ensures that the SSH connection lasts for 300 seconds before the connection is timed out.

It is also advisable to set a timeout value when accessing machines from hosting platforms to avoid high run-up costs especially when their billings are per minute.

When using the client machine for ssh connection, your updated config values in the file $HOME/.ssh/config will look like this:

Host * ServerAliveInterval 300 ServerAliveCountMax 2

When using a server machine for an ssh connection, your updated config values in the file /etc/ssh/ssh_config will look like this:

ClientAliveInterval 300 ClientAliveCountMax 2

We can now comfortably handle ssh sessions without worrying about unexpected timeouts. Hope you enjoyed the article. Feel free to leave a comment or feedback.

Источник

Set SSH connection timeout

I’m trying to cut down the time ssh is trying to open a connection to a host. If I put for example ssh www.google.com it takes very long until the prompt comes back. I read about using ssh -o ConnectTimeout=10 www.google.com instead, but even this takes very long. Is there maybe a number of attemps I can modify to decrease the blocking time?

from ssh docs: «Use this to specifies the timeout (in seconds) used when connecting to the SSH server, instead of using the default system TCP timeout. This value is used only when the target is down or really unreachable, not when it refuses the connection.»

2 Answers 2

The problem may be that ssh is trying to connect to all the different IPs that www.google.com resolves to. For example on my machine:

# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012 debug1: Connecting to www.google.com [173.194.43.20] port 22. debug1: connect to address 173.194.43.20 port 22: Connection timed out debug1: Connecting to www.google.com [173.194.43.19] port 22. debug1: connect to address 173.194.43.19 port 22: Connection timed out debug1: Connecting to www.google.com [173.194.43.18] port 22. debug1: connect to address 173.194.43.18 port 22: Connection timed out debug1: Connecting to www.google.com [173.194.43.17] port 22. debug1: connect to address 173.194.43.17 port 22: Connection timed out debug1: Connecting to www.google.com [173.194.43.16] port 22. debug1: connect to address 173.194.43.16 port 22: Connection timed out ssh: connect to host www.google.com port 22: Connection timed out 

If I run it with a specific IP, it returns much faster.

EDIT: I’ve timed it (with time ) and the results are:

Источник

Как увеличить время ожидания SSH-соединения в Linux

Команды LINUX «от A до Z» — настольная книга с примерами

timeOut of SSH

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

Читайте также:  Linux traceroute with icmp

Увеличьте время ожидания соединения SSH

На сервере перейдите в файл конфигурации /etc/sshsshd_config.

Прокрутите и найдите следующие параметры:

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

С другой стороны, параметр ClientAliveCountMax определяет количество живых сообщений клиента, которые отправляются без получения каких-либо сообщений от клиента. Если этот предел достигнут во время отправки сообщений, демон sshd прекратит сеанс, фактически завершив сеанс ssh.

Значение времени ожидания определяется произведением вышеуказанных параметров, т.е.

Курсы Python с нуля до DevOps на практике за 1,5 часа

Например, допустим, вы определили свои параметры, как показано:

Increase-SSH-Timeout

Значение времени ожидания будет 1200 секунд * 3 = 3600 секунд. Это эквивалентно 1 часу, что означает, что ваш ssh-сеанс будет работать в течение простоя в течение 1 часа без сброса.

Кроме того, вы можете достичь того же результата, указав только параметр ClientAliveInterval.

После этого перезагрузите демон OpenSSH, чтобы изменения вступили в силу.

Вывод

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

Курсы Git за час: руководство для начинающих DevOps / DevNet инженеров

Спасибо за уделенное время на прочтение статьи о том, как работает SSH-соединения в Linux!

Если возникли вопросы, задавайте их в комментариях.

Подписывайтесь на обновления нашего блога и оставайтесь в курсе новостей мира инфокоммуникаций!

Курсы Cisco, Linux, кибербезопасность, DevOps / DevNet, Python с трудоустройством!

Спешите подать заявку! Группы стартуют 25 января, 26 февраля, 22 марта, 26 апреля, 24 мая, 21 июня, 26 июля, 23 августа, 20 сентября, 25 октября, 22 ноября, 20 декабря.

  • Поможем стать экспертом по сетевой инженерии, кибербезопасности, программируемым сетям и системам и получить международные сертификаты Cisco, Linux LPI, Python Institute.
  • Предлагаем проверенную программу с лучшими учебниками от экспертов из Cisco Networking Academy, Linux Professional Institute и Python Institute, помощь сертифицированных инструкторов и личного куратора.
  • Поможем с трудоустройством и стартом карьеры в сфере IT — 100% наших выпускников трудоустраиваются.
  • Проведем вечерние онлайн-лекции на нашей платформе.
  • Согласуем с вами удобное время для практик.
  • Если хотите индивидуальный график — обсудим и реализуем.
  • Личный куратор будет на связи, чтобы ответить на вопросы, проконсультировать и мотивировать придерживаться сроков сдачи экзаменов.
  • Всем, кто боится потерять мотивацию и не закончить обучение, предложим общение с профессиональным коучем.
  • отредактировать или создать с нуля резюме;
  • подготовиться к техническим интервью;
  • подготовиться к конкурсу на понравившуюся вакансию;
  • устроиться на работу в Cisco по специальной программе. Наши студенты, которые уже работают там: жмите на #НашиВCisco Вконтакте, #НашиВCisco Facebook.

Чтобы учиться на курсах Cisco, Linux LPI, кибербезопасность, DevOps / DevNet, Python, подайте заявку или получите бесплатную консультацию.

Источник

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