diff --git a/mreg_cli/main.py b/mreg_cli/main.py index e32b65f6..98f00c92 100644 --- a/mreg_cli/main.py +++ b/mreg_cli/main.py @@ -112,6 +112,18 @@ def main(): metavar="SOURCE", ) + output_args.add_argument( + "--token-only", + dest="token_only", + action="store_true", + default=False, + help="Only attempt token login, this will avoid interactive prompts.", + ) + + output_args.add_argument( + "command", metavar="command", nargs="*", help="Oneshot command to issue to the cli." + ) + args = parser.parse_args() setup_logging(args.verbosity) logger.debug(f"args: {args}") @@ -135,7 +147,10 @@ def main(): return try: - try_token_or_login(config.get("user"), config.get("url")) + try_token_or_login( + config.get("user"), config.get("url"), fail_without_token=args.token_only + ) + except (EOFError, KeyboardInterrupt, LoginFailedError) as e: print(e) raise SystemExit() from None @@ -171,6 +186,16 @@ def get_prompt_message(): cli.process_command_line(command) return + # Check if we got a oneshot command. If so, execute it and exit. + if args.command: + cmd = " ".join(args.command) + try: + cli.process_command_line(cmd) + except ValueError as e: + print(e) + + raise SystemExit() from None + # The app runs in an infinite loop and is expected to exit using sys.exit() while True: try: diff --git a/mreg_cli/utilities/api.py b/mreg_cli/utilities/api.py index 3719fe81..ae82a04f 100644 --- a/mreg_cli/utilities/api.py +++ b/mreg_cli/utilities/api.py @@ -52,7 +52,7 @@ def set_file_permissions(f: str, mode: int) -> None: pass -def try_token_or_login(user: str, url: str) -> None: +def try_token_or_login(user: str, url: str, fail_without_token: bool = False) -> None: """Check for a valid token or interactively log in to MREG. Exits on connection failure. @@ -90,6 +90,8 @@ def try_token_or_login(user: str, url: str) -> None: error(f"Could not connect to {url}") if ret.status_code == 401: + if fail_without_token: + raise SystemExit("Token only login failed.") prompt_for_password_and_login(user, url, catch_exception=False)