@@ -511,6 +511,60 @@ def test_run_shell_command_sudo_password_prompt(
511511 "sudo -H -A -k sh -c 'echo Šablony'"
512512 ), get_pty = False )
513513
514+ @patch ('pyinfra.api.connectors.util.getpass' )
515+ @patch ('pyinfra.api.connectors.util.get_sudo_askpass_exe' )
516+ @patch ('pyinfra.api.connectors.ssh.SSHClient' )
517+ @patch ('pyinfra.api.connectors.ssh.SFTPClient' )
518+ def test_run_shell_command_sudo_password_automatic_prompt (
519+ self ,
520+ fake_sftp_client ,
521+ fake_ssh_client ,
522+ fake_get_sudo_askpass_exe ,
523+ fake_getpass ,
524+ ):
525+ fake_ssh = MagicMock ()
526+ first_fake_stdout = MagicMock ()
527+ second_fake_stdout = MagicMock ()
528+
529+ first_fake_stdout .__iter__ .return_value = ['sudo: a password is required' ]
530+
531+ fake_ssh .exec_command .side_effect = [
532+ (MagicMock (), first_fake_stdout , MagicMock ()), # command w/o sudo password
533+ (MagicMock (), MagicMock (), MagicMock ()), # command to chmod askpass file
534+ (MagicMock (), second_fake_stdout , MagicMock ()), # command with sudo pw
535+ ]
536+
537+ fake_ssh_client .return_value = fake_ssh
538+ fake_getpass .return_value = 'password'
539+
540+ inventory = make_inventory (hosts = ('somehost' ,))
541+ State (inventory , Config ())
542+ host = inventory .get_host ('somehost' )
543+ host .connect ()
544+
545+ command = 'echo Šablony'
546+ first_fake_stdout .channel .recv_exit_status .return_value = 1
547+ second_fake_stdout .channel .recv_exit_status .return_value = 0
548+
549+ out = host .run_shell_command (command , sudo = True , print_output = True )
550+ assert len (out ) == 3
551+
552+ status , stdout , stderr = out
553+ assert status is True
554+
555+ fake_sftp_client .from_transport ().putfo .assert_called_with (
556+ fake_get_sudo_askpass_exe .return_value , 'pyinfra-sudo-askpass' ,
557+ )
558+
559+ fake_ssh .exec_command .assert_any_call ((
560+ "sudo -H -n sh -c 'echo Šablony'"
561+ ), get_pty = False )
562+
563+ fake_ssh .exec_command .assert_called_with ((
564+ 'env SUDO_ASKPASS=pyinfra-sudo-askpass PYINFRA_SUDO_PASSWORD=password '
565+ "sudo -H -A -k sh -c 'echo Šablony'"
566+ ), get_pty = False )
567+
514568 # SSH file put/get tests
515569 #
516570
0 commit comments