Guest User

hdhomerun_check.py

a guest
Jan 4th, 2023
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.91 KB | None | 0 0
  1. $ cat hdhomerun_check.py
  2. #!/usr/bin/python3
  3. # -*- coding: utf-8 -*-
  4.  
  5. """ See if the HD Homerun box is accessible and running
  6.  
  7. Can be called with a optional IP address(s) for users that
  8. have multiple HDHRs that have STATIC addresses.
  9.  
  10. Expects a writable log file in /tmp named hdhr_discovery.log.
  11. Owner:group = mythtv:mythtv and mode = 664. If your user is a
  12. member of the mythtv group, then this can be run by you from
  13. the command line assuming the permissions are 0664.
  14.  
  15. Exit codes are:
  16.  
  17.    5 times the number of failing HDHRs
  18.    4 if the user running the program isn't what systemd is using
  19.    3 if the logfile isn't writable
  20.    2 for a keyboard interrupt
  21.    1 no discovery output or IPv4 and IPv6 address found
  22.    0 if all HDHR(s) are found (success case)
  23. """
  24.  
  25. __version__ = '1.14'
  26.  
  27. import argparse
  28. import getpass
  29. import subprocess
  30. import sys
  31. import logging
  32. from time import sleep
  33. from datetime import datetime
  34.  
  35. ATTEMPTS = 21
  36. DELAY = 2
  37.  
  38.  
  39. # pylint: disable=consider-using-f-string,consider-using-with
  40. def get_program_arguments():
  41.     ''' Process the command line. '''
  42.  
  43.     parser = argparse.ArgumentParser(description='HDHR Access Test',
  44.                                      epilog='*  Default values are in ()s.')
  45.  
  46.     parser.add_argument('IP_ADDRESSES', type=str, metavar='<IP>', default=None,
  47.                         nargs='*', help='Optional IP address(s) (%(default)s)')
  48.  
  49.     parser.add_argument('--logfile', default='/tmp/hdhr_discovery.log',
  50.                         type=str, metavar='<lf>',
  51.                         help='Location of log file (%(default)s)')
  52.  
  53.     parser.add_argument('--version', action='version',
  54.                         version='%(prog)s ' + __version__)
  55.  
  56.     return vars(parser.parse_args())
  57.  
  58.  
  59. def get_elapsed_time(start):
  60.     ''' Calculate the time spent waiting for the HDHR to come up '''
  61.  
  62.     delta = datetime.utcnow() - start
  63.     rounded_delta = '{:.3f}'.format(delta.seconds +
  64.                                     (delta.microseconds / 1000000))
  65.     return rounded_delta
  66.  
  67.  
  68. def main(ip_address, logfile):
  69.     ''' Try to discover the HDHR(s) '''
  70.  
  71.     attempt = 0  # Shut up pylint.
  72.     command = ['systemctl', 'show', '--property=User', '--value',
  73.                'mythtv-backend.service']
  74.  
  75.     systemd_user = subprocess.check_output(command, stderr=subprocess.STDOUT).\
  76.                                            strip().decode()
  77.     if not systemd_user:
  78.         systemd_user = 'root'
  79.  
  80.     if getpass.getuser() != systemd_user:
  81.         print('BE running as user %s, not your user, aborting!' % systemd_user)
  82.         sys.exit(4)
  83.  
  84.     if ip_address is None:
  85.         command = ['hdhomerun_config', 'discover']
  86.     else:
  87.         command = ['hdhomerun_config', 'discover', ip_address]
  88.  
  89.     logger = logging.getLogger(command[0])
  90.  
  91.     try:
  92.         logging.basicConfig(filename=logfile, filemode='a',
  93.                             format='%(asctime)s %(levelname)s\t%(message)s',
  94.                             datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO)
  95.     except PermissionError:
  96.         print('%s is not writable, aborting!' % logfile)
  97.         sys.exit(3)
  98.  
  99.     logger.info('Starting HD Homerun discovery')
  100.  
  101.     start = datetime.utcnow()
  102.  
  103.     for attempt in range(1, ATTEMPTS):
  104.         try:
  105.             discovery_response = subprocess.check_output(command,
  106.                                     stderr=subprocess.STDOUT).decode().split()
  107.         except KeyboardInterrupt:
  108.             sys.exit(2)
  109.         except subprocess.CalledProcessError:
  110.             logger.warning('%s failed, keep looking.', command[0])
  111.             sleep(DELAY)
  112.             continue
  113.  
  114.         if not discovery_response:
  115.             logger.error('No output from %s, aborting!', command)
  116.             sys.exit(1)
  117.  
  118.         if len(discovery_response) > 6:
  119.             logger.error('%s got multiple IPs. Disable IPv6, aborting!',
  120.                          command)
  121.             sys.exit(1)
  122.  
  123.         if discovery_response[0] != 'hdhomerun':
  124.             logger.warning('%s got an unexpected response.', command)
  125.             sleep(DELAY)
  126.         else:
  127.             logger.info('Found HD Homerun%s. Seconds=%s, attempts=%d.',
  128.                         '' if ip_address is None else (' for ' + ip_address),
  129.                         get_elapsed_time(start), attempt)
  130.             return 0
  131.  
  132.     logger.error('Couldn\'t find any HD Homerun%s. Seconds=%s, attempts=%d.',
  133.                  '' if ip_address is None else (' for ' + ip_address),
  134.                  get_elapsed_time(start), attempt)
  135.  
  136.     return 5
  137.  
  138.  
  139. if __name__ == '__main__':
  140.  
  141.     ARGS = get_program_arguments()
  142.  
  143.     if not ARGS['IP_ADDRESSES']:
  144.         RETURN_VALUE = main(None, ARGS['logfile'])
  145.     else:
  146.         RETURN_VALUE = 0
  147.         for address in ARGS['IP_ADDRESSES']:
  148.             RETURN_VALUE += main(address, ARGS['logfile'])
  149.  
  150.     sys.exit(RETURN_VALUE)
  151.  
  152. # vim: set expandtab tabstop=4 shiftwidth=4 smartindent colorcolumn=80:
Advertisement
Add Comment
Please, Sign In to add comment