Wrapper for commands to be run as root
(command, tty, sudo, allow_failure=False, **kwargs)
| 2398 | |
| 2399 | |
| 2400 | def root_cmd(command, tty, sudo, allow_failure=False, **kwargs): |
| 2401 | """ |
| 2402 | Wrapper for commands to be run as root |
| 2403 | """ |
| 2404 | logging_command = command |
| 2405 | sudo_password = kwargs.get("sudo_password", None) |
| 2406 | |
| 2407 | if sudo: |
| 2408 | if sudo_password is None: |
| 2409 | command = f"sudo {command}" |
| 2410 | logging_command = command |
| 2411 | else: |
| 2412 | logging_command = f'sudo -S "XXX-REDACTED-XXX" {command}' |
| 2413 | command = f"sudo -S {command}" |
| 2414 | |
| 2415 | log.debug("Using sudo to run command %s", logging_command) |
| 2416 | |
| 2417 | ssh_args = [] |
| 2418 | |
| 2419 | if tty: |
| 2420 | # Use double `-t` on the `ssh` command, it's necessary when `sudo` has |
| 2421 | # `requiretty` enforced. |
| 2422 | ssh_args.extend(["-t", "-t"]) |
| 2423 | |
| 2424 | known_hosts_file = kwargs.get("known_hosts_file", "/dev/null") |
| 2425 | host_key_checking = "no" |
| 2426 | if known_hosts_file != "/dev/null": |
| 2427 | host_key_checking = "yes" |
| 2428 | |
| 2429 | ssh_args.extend( |
| 2430 | [ |
| 2431 | # Don't add new hosts to the host key database |
| 2432 | f"-oStrictHostKeyChecking={host_key_checking}", |
| 2433 | # Set hosts key database path to /dev/null, i.e., non-existing |
| 2434 | f"-oUserKnownHostsFile={known_hosts_file}", |
| 2435 | # Don't re-use the SSH connection. Less failures. |
| 2436 | "-oControlPath=none", |
| 2437 | ] |
| 2438 | ) |
| 2439 | |
| 2440 | if "key_filename" in kwargs: |
| 2441 | # There should never be both a password and an ssh key passed in, so |
| 2442 | ssh_args.extend( |
| 2443 | [ |
| 2444 | # tell SSH to skip password authentication |
| 2445 | "-oPasswordAuthentication=no", |
| 2446 | "-oChallengeResponseAuthentication=no", |
| 2447 | # Make sure public key authentication is enabled |
| 2448 | "-oPubkeyAuthentication=yes", |
| 2449 | # do only use the provided identity file |
| 2450 | "-oIdentitiesOnly=yes", |
| 2451 | # No Keyboard interaction! |
| 2452 | "-oKbdInteractiveAuthentication=no", |
| 2453 | # Also, specify the location of the key file |
| 2454 | "-i {}".format(kwargs["key_filename"]), |
| 2455 | ] |
| 2456 | ) |
| 2457 | if "ssh_timeout" in kwargs: |
no test coverage detected