Skip to content

Commit dc3e312

Browse files
committed
connectors: improve detection of sudo password needed
It's possible the line we're looking for is *not* the last line of the output so search backwards through everything for it.
1 parent 4fe73f4 commit dc3e312

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

pyinfra/connectors/util.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -198,14 +198,18 @@ def execute_command_with_sudo_retry(
198198
) -> tuple[int, CommandOutput]:
199199
return_code, output = execute_command()
200200

201+
# If we failed look for a sudo password prompt line and re-submit using the sudo password. Look
202+
# at all lines here in case anything else gets printed, eg in:
203+
# https://github.com/pyinfra-dev/pyinfra/issues/1292
201204
if return_code != 0 and output and output.combined_lines:
202-
last_line = output.combined_lines[-1].line
203-
if last_line.strip() == "sudo: a password is required":
204-
# If we need a password, ask the user for it and attach to the host
205-
# internal connector data for use when executing future commands.
206-
sudo_password = getpass("{0}sudo password: ".format(host.print_prefix))
207-
host.connector_data["prompted_sudo_password"] = sudo_password
208-
return_code, output = execute_command()
205+
for line in reversed(output.combined_lines):
206+
if line.line.strip() == "sudo: a password is required":
207+
# If we need a password, ask the user for it and attach to the host
208+
# internal connector data for use when executing future commands.
209+
sudo_password = getpass("{0}sudo password: ".format(host.print_prefix))
210+
host.connector_data["prompted_sudo_password"] = sudo_password
211+
return_code, output = execute_command()
212+
break
209213

210214
return return_code, output
211215

@@ -304,7 +308,7 @@ def make_unix_command(
304308
_sudo=False,
305309
_sudo_user=None,
306310
_use_sudo_login=False,
307-
_sudo_password=False,
311+
_sudo_password="",
308312
_sudo_askpass_path=None,
309313
_preserve_sudo_env=False,
310314
# Doas config

0 commit comments

Comments
 (0)