Can I prevent a remote Mac from entering sleep via a remote ssh connection?

Caffeine prevents your Mac from falling asleep. Maybe, it can help you out with your issue too. The sleep isn't at all random, but in fact is set in the Energy Saver system preference as well from the terminal using pmset.

You could use pmset to inspect and change the sleep settings if you have admin rights on the remote.


On macOS 11.5.1 Big Sur, you can use systemsetup to alter sleep settings:

# Disable display, disk, computer sleep
sudo systemsetup -setsleep Never