registerups: Reworked configuration parsing.

It looks more complicated, but contains error handling.
This commit is contained in:
Sergey Morozov 2019-08-26 14:52:27 +03:00
parent 34fc66d20e
commit 098714d37d
2 changed files with 39 additions and 18 deletions

View File

@ -2,7 +2,6 @@
# IP addres or hostname of UPS SNMP card
address = 192.168.0.105
# TCP port
# default - 3052
port = 3052
# Secret phrase for software authentication. This value must be the
# same as configured on the UPS web interface

View File

@ -78,30 +78,52 @@ class cps_ups:
def help():
print('Usage: ' + sys.argv[0] + ' <path-to-configuration-file>')
configuration_structure = {'UPS': ['address',
'secret_key',
'port'],
'HOST': ['ip_address',
'shutdown_time',
'delay_time',
'hostname',
'outlet_id',
'bank_id',
'isps',
'contact',
'location',
'bedt']}
try:
configfile = sys.argv[1]
except IndexError:
help()
sys.exit(1)
if not os.path.isfile(configfile):
print('Error: configuration file ' + configfile + ' doesn\'t exists')
sys.exit(2)
configuration = {}
try:
config = configparser.ConfigParser()
config.read(configfile)
for section in configuration_structure:
configuration[section] = {}
for param in configuration_structure[section]:
configuration[section][param] = config.get(section, param)
except (configparser.NoOptionError,
configparser.MissingSectionHeaderError,
configparser.ParsingError) as err:
print('Configuration file parsing error:\n' + str(err))
sys.exit(3)
u = cps_ups(address = config.get('UPS', 'address'),
secret_key = config.get('UPS','secret_key'),
port = int(config.get('UPS', 'port', fallback='3052')))
u = cps_ups(address = configuration['UPS']['address'],
secret_key = configuration['UPS']['secret_key'],
port = int(configuration['UPS']['port']))
u.register(ip_address = config.get('HOST','ip_address'),
shutdown_time = config.get('HOST','shutdown_time'),
delay_time = config.get('HOST','delay_time'),
hostname = config.get('HOST','hostname'),
outlet_id = config.get('HOST','outlet_id'),
bank_id = config.get('HOST','bank_id'),
isps = config.get('HOST','isps'),
contact = config.get('HOST','contact'),
location = config.get('HOST','location'),
bedt = config.get('HOST','bedt'))
u.register(ip_address = configuration['HOST']['ip_address'],
shutdown_time = configuration['HOST']['shutdown_time'],
delay_time = configuration['HOST']['delay_time'],
hostname = configuration['HOST']['hostname'],
outlet_id = configuration['HOST']['outlet_id'],
bank_id = configuration['HOST']['bank_id'],
isps = configuration['HOST']['isps'],
contact = configuration['HOST']['contact'],
location = configuration['HOST']['location'],
bedt = configuration['HOST']['bedt'])