Keep Alive your Plex Media Server (PMS)

Let’s say you want to have a script run every 1 min to check to see if plex media server is running. If its not, re-launch it and send me an email when it does so. If its still running; don’t bother to inform me.

Sounds simple. And for the non-unix savvy people this might be a little hard to digest. You need 3 things:

  1. You need the script to check the Plex Media Server is running or not
  2. You need to install the script as a cronjob
  3. You need to have postfix setup so when the job fails it can send you an email

The Plex Media Script (plexchecker.py):


#!/usr/bin/python
__doc__ = """
Plex Media Server Startup if closed cronjob
"""
#
import os
import sys

import subprocess

PIPE = subprocess.PIPE

def start_plex():
    return os.system('open -a "Plex Media Server" &')

if __name__ == '__main__':
    # [] around P ignores self matching
    cmd = "ps aux |grep '/[P]lex Media Server' | awk '{print $2}' | head -1"

    pid = subprocess.Popen(cmd,shell=True, stdout=PIPE, stderr=PIPE).communicate()[0]
    pid = pid.strip()
    if pid == "":
        print cmd
        print "pid='%s'" % pid
        print "no process found, starting plex media server"
        sys.exit(start_plex())
        print "done."

    sys.exit(0)

I saved the script in my user accounts “bin” directory. Open a terminal (located in /Applications/Utilities/Terminal.app).
% mkdir ~/bin
* anytime you see “%” that means shell command.
And save the script in your ~/bin/ directory. You may use any text editor you wish. I personally use gvim but its a little hard for new users to use. Something better like BBEdit or Eclipse is recommended for new programmers.

Setup Your POSTFIX email:
Why do you need this step? Well, this is only needed if you want to recieve an email anytime your cronjob fails or succeeds. If you don’t care, you can skip down to the cronjob section.
The next part is setting up postfix. Note that everything here uses “gmail” but you can use any provider you want. I only recommend gmail since  you can setup a generic account that you send your alerts too. We need to create a text file for postfix first:
% sudo touch /etc/postfix/sasl_passwd
% sudo vi /etc/postfix/sasl_passwd

(type i – for insert mode), and put the following in the file:
smtp.gmail.com:587 user_account@gmail.com:password_for_your_email
– replace user_account, with your gmail account
– replace password_for_your_email with your gmail password
(type :wq, the : means vi is looking for a command, w means write, q means quite, so :wq does it all at once)
% sudo postmap -q smpt.gmail.com:587 /etc/postfix/sasl_passwd
This installs the username and password into the postfix db file so its encrypted

Now that you have the password setup. We need to configure the server:
% sudo vi /etc/postfix/main.cf
Scroll to the bottom of the file and add:

relayhost=smtp.gmail.com:587
smtpd_sasl_auth_enable = yes
smtpd_sasl_path = smtpd
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_type = cyrus
smtp_sasl_auth_enable = yes
# Enable Transport Layer Security (TLS), i.e. SSL.
smtp_use_tls=yes
smtp_tls_security_level=encrypt
tls_random_source=dev:/dev/urandom

( type :wq when done, remember the shift semi-colin is a command in vi)

Ok, now to start the server and test it:
% sudo postfix start
After, type:
% date | mail -s testing.a user_account@gmail.com
You should get an email after a few minutes; check your spam folder since gmail is probably thinking this is spam. You may have to re-read / re-do this a few times if you are new to linux. Even me (a pro) it took a few times before I got it working. Typo’s all over the place.

Check the internal mail server:
% mailq
Check the postfix for your logged in account
% mail

As always, use “man” to get the manual for these commands (e.g. man mail) for help.

Setup your Cronjob:
Phew, lots of info. Ok, so we have postfix started, we have our file we need for our cronjob. Now to setup the cron.
% crontab -e

# min(0-59) hour(0-23)  day(1-31)   month(1-12) day (0-6)
# *         *           *           *           *       # script to run
MAILTO=user_account@gmail.com
*/1 *   *   *   *   /Users/mac_account/bin/plexchecker.py 

Notice user_account@gmail, this tells the cron to send the email if something fails to this account. The /User/mac_account/ folder is your home folder. On linux it would be /home/user_account/ for example. To keep things simple you probally should have your mac_account on your machine be the same as you gmail account.

When done inserting the code above for crontab, type :wq, notice that crontab used vi, this is why its a good idea to know a little vi.

So, to summarize what will happen here. The cronjob will run every 1 minute, if the plex server is not running, nothing is printed by the “plexchecker.py” script. If “ANY” text is printed via the script to standard output (e.g. print statement in python) or any errors are found (e.g. standard error) the cron will send you an email to the account specified in “MAILTO”.

Lastly, please let me know if this works for you. It took a few hours for me to get this up and running. I will modify/update the page if you find errors or I am missing a step.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: