UPDATE: The below script works for Linux versions running sleep.d, like Mint <= 17.3 or Ubuntu 14.06. For a version that works on systems running systemd, including Mint 18 and Ubuntu > 15.04 see my update.


I recently set up a Plex server on a Linux Mint desktop. To save energy, I don’t want the thing running all the time, so I have it set to suspend after 15 minutes and then wake-on-LAN when I want to start using it. However, it will put itself to sleep even while in the middle of streaming a video. Not finding any reasonable solutions online, I came up with this script to keep it awake until after the video is finished. I’m using it in Linux Mint, but it should work with other Ubuntu-like systems too.

Create a new file under /etc/pm/sleep.d/, with root privileges. I called it 05_plexkeepawake. Put the following code in the file:

#!/bin/bash
 case "$1" in
     suspend)
         s=$(curl localhost:32400/status/sessions 2&gt;/dev/null | sed -n "s/.*MediaContainer size=\"\(.*\)\".*//p" )
     if [ $s -gt 0 ]
     then
         echo "Plex session active, cancel suspend"
         exit 1;
     fi
 esac

Give the script executable permission:

sudo chmod +x 05_plexkeepawake

I had to install curl for this to work, apparently it’s not installed by default in Mint:

sudo apt-get install curl

All the scripts in the /etc/pm/sleep.d folder will run just before suspend. If any of them return something other than 0, the suspend will be canceled. In this case, we check a local webpage hosted by Plex, and strip out the number of active sessions. If there’s 1 or more, then something is streaming, and suspend is canceled. Once the video is done, the machine can go to sleep as usual.