I use argparse and eval to change loglevels of logging.
parser = argparse.ArgumentParser(
description="Adds New Location to the Snipe-IT Server")
parser.add_argument('-l', '--loglevel', type=str, default='WARNING', choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'])
args = parser.parse_args()
logging.basicConfig(level=eval(f"logging.{args.loglevel}"))
I wonder if it is save to use eval in this case? I don’t know if choices limit in this case the inputs.
>Solution :
No, it is not safe. It won’t be too hard for a knowledgable malicious user to hack the argparse module to be able to pass any thing they want through the CLI.
However, at this point they might as well just write their own malicious program than trying to use yours as an attack vector.
Regardless, just use getattr. eval is almost never the correct solution.
logging.basicConfig(level=getattr(logging, args.loglevel))