Add a timeout to the SSH connection

paramiko's connect had no timeout, so a server that doesn't answer
made the program hang until the OS gave up (about 2 minutes). Give up
after 15 seconds and exit with code 5.
This commit is contained in:
Fuxino
2026-10-08 20:45:07 +02:00
parent cd80c941ad
commit 28d1b0d0d0
+7 -4
View File
@@ -69,6 +69,9 @@ if journal:
P = ParamSpec('P') P = ParamSpec('P')
R = TypeVar('R') R = TypeVar('R')
# Seconds to wait for the TCP connection to the SSH server
SSH_TIMEOUT = 15
def timing(func: Callable[P, R]) -> Callable[P, R]: def timing(func: Callable[P, R]) -> Callable[P, R]:
"""Decorator to measure execution time of a function """Decorator to measure execution time of a function
@@ -401,7 +404,7 @@ class Backup:
# WarningPolicy emits a UserWarning for unknown host keys # WarningPolicy emits a UserWarning for unknown host keys
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter('error', UserWarning) warnings.simplefilter('error', UserWarning)
ssh.connect(self.ssh_host, username=self.ssh_user) ssh.connect(self.ssh_host, username=self.ssh_user, timeout=SSH_TIMEOUT)
return ssh return ssh
except UserWarning: except UserWarning:
@@ -427,7 +430,7 @@ class Backup:
pass pass
try: try:
ssh.connect(self.ssh_host, username=self.ssh_user) ssh.connect(self.ssh_host, username=self.ssh_user, timeout=SSH_TIMEOUT)
return ssh return ssh
except paramiko.SSHException: except paramiko.SSHException:
@@ -441,7 +444,7 @@ class Backup:
password = getpass( password = getpass(
f'{self.ssh_user}@{self.ssh_host}\'s password: ') f'{self.ssh_user}@{self.ssh_host}\'s password: ')
ssh.connect(self.ssh_host, username=self.ssh_user, ssh.connect(self.ssh_host, username=self.ssh_user, timeout=SSH_TIMEOUT,
password=password) password=password)
self._password_auth = True self._password_auth = True
@@ -465,7 +468,7 @@ class Backup:
return None return None
try: try:
ssh.connect(self.ssh_host, username=self.ssh_user, pkey=pkey) ssh.connect(self.ssh_host, username=self.ssh_user, timeout=SSH_TIMEOUT, pkey=pkey)
except paramiko.SSHException: except paramiko.SSHException:
logger.critical('SSH connection to server failed') logger.critical('SSH connection to server failed')