It is possible to prevent the SSH session from being closed due to inactivity
This behavior is a default security measure to prevent an open session from being exposed on an unattended system, but it can be easily changed.
The disconnection occurs because your Mac’s SSH client or Ubuntu’s SSH server (or both) are configured to close the connection after a period of inactivity, i.e., when no data is being sent.
To solve this, you can set up a “keep-alive” to send data packets at regular intervals and keep the connection active.
This can be done on the client (your Mac) or on the server (Ubuntu). The most common and recommended way to configure this is on the client.
That is, you have 2 options to do it
option 1:
configure on the client
Edit the SSH configuration file
~/.ssh/config
If the file doesn’t exist, just create it.
Add the following lines to the file:
Host *
ServerAliveInterval 60
Host *: This line will apply the setting to all your SSH connections. If you only want it to apply to a specific server, you can replace * with the server’s IP or hostname.
ServerAliveInterval 60: This tells your SSH client to send a keep-alive packet to the server every 60 seconds if it has not received data.
The next time you connect via SSH, your session will not be logged out due to inactivity.
option 2:
Configure on the server
This option requires administrator permissions on the server and will affect all users connecting to it.
Edit the SSH daemon configuration file sshd_config located at:
/etc/ssh
Find the following lines and either uncomment them (if they have a # at the beginning) or add them:
ClientAliveInterval 60
ClientAliveCountMax 2

ClientAliveInterval 60: The server will send a keep-alive message to the client every 60 seconds if it is idle.
ClientAliveCountMax 2: If the client does not respond to 2 consecutive keep-alive messages, the server will close the connection.
Save the changes and restart the SSH service for the changes to take effect:
sudo systemctl restart sshd
The recommended way is to do it from the client, since it is specific and you do it for 1 user, on the server side it is generalized