From 8472b394ee44cd46cc36fd4fe0a4882364cab602 Mon Sep 17 00:00:00 2001 From: Sam Chudnick Date: Sat, 2 Jul 2022 15:35:50 -0400 Subject: Read options from config file Set a standardized configuration file location and read options from there. Allow for specifiying alternate location on command line. Options can still be specified on the command line, and any command line options take priority over those given in the configuration file. --- pam/pam.py | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) (limited to 'pam/pam.py') diff --git a/pam/pam.py b/pam/pam.py index 5a2fee8..5cb9f4d 100755 --- a/pam/pam.py +++ b/pam/pam.py @@ -3,6 +3,8 @@ import socket import argparse import time import sys +import configparser +import os # Sends authentication request to MFA server # Receive either pass or fail response from MFA server @@ -40,7 +42,6 @@ def init_connection(mfa_server, pam_port): while connection == None and timeout < timeout_length: try: connection = socket.create_connection((mfa_server,pam_port)) - print("connected to mfa server") return connection except (ConnectionError,ConnectionRefusedError): time.sleep(sleep_length) @@ -63,19 +64,54 @@ def read_config(config_file): port = int(line.split("=")[1].strip()) return (server,port) + +def read_config(config_file): + parser = configparser.ConfigParser(inline_comment_prefixes="#") + parser.read(config_file) + return parser + + +def get_vars(args,confparser): + if not os.path.exists(args.config): + print("Unable to open config file") + sys.exit(1) + + server = None + port = None + + # Set values from config file first + if confparser.has_section("pam"): + server = confparser.get("pam","server",fallback=None) + port = confparser.get("pam","port",fallback=None) + + # Let command line args overwrite any values + if args.server: + server = args.server + if args.port: + port = args.port + + # Exit if any value is null + if None in [server,port]: + print("error: one or more items unspecified") + sys.exit(1) + + return server,port + + def main(): authed = "0" failed = "1" # Get arguments args = parse_arguments() + confparser = read_config(args.config) + mfa_server,pam_port = get_vars(args,confparser) user = args.user service = args.service # Compile data to send to server # Read server and port from config file but allow command line options # to override those settings - mfa_server, pam_port = read_config(args.config) if args.server != None: mfa_server = args.server if args.port != None: -- cgit v1.2.3