Skip to content

Commit

Permalink
Allow oneshot commands from the terminal. (#208)
Browse files Browse the repository at this point in the history
* Allow oneshot commands from the terminal.

This patch allows the use of mreg-cli without interaction, ala:

`mreg-cli host info foo`

This will then feed the command `host info foo` to the cli and then exit.

Also adds an option to force token only login. Good for scripts. :)
  • Loading branch information
terjekv authored Feb 12, 2024
1 parent 09139a8 commit 0cbd52a
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 2 deletions.
27 changes: 26 additions & 1 deletion mreg_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down
4 changes: 3 additions & 1 deletion mreg_cli/utilities/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)


Expand Down

0 comments on commit 0cbd52a

Please sign in to comment.