multiCMD 1.71__tar.gz → 1.72__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. {multicmd-1.71 → multicmd-1.72}/PKG-INFO +33 -7
  2. {multicmd-1.71 → multicmd-1.72}/README.md +32 -6
  3. {multicmd-1.71 → multicmd-1.72}/multiCMD.egg-info/PKG-INFO +33 -7
  4. {multicmd-1.71 → multicmd-1.72}/multiCMD.py +54 -33
  5. {multicmd-1.71 → multicmd-1.72}/tests/test_api.py +6 -1
  6. {multicmd-1.71 → multicmd-1.72}/tests/test_async_executor.py +17 -1
  7. {multicmd-1.71 → multicmd-1.72}/tests/test_env.py +4 -4
  8. {multicmd-1.71 → multicmd-1.72}/tests/test_interrupts.py +1 -1
  9. {multicmd-1.71 → multicmd-1.72}/tests/test_parsing.py +3 -3
  10. {multicmd-1.71 → multicmd-1.72}/tests/test_pool.py +3 -3
  11. {multicmd-1.71 → multicmd-1.72}/tests/test_sudo.py +111 -18
  12. {multicmd-1.71 → multicmd-1.72}/tests/test_supervision.py +2 -3
  13. {multicmd-1.71 → multicmd-1.72}/LICENSE +0 -0
  14. {multicmd-1.71 → multicmd-1.72}/multiCMD.egg-info/SOURCES.txt +0 -0
  15. {multicmd-1.71 → multicmd-1.72}/multiCMD.egg-info/dependency_links.txt +0 -0
  16. {multicmd-1.71 → multicmd-1.72}/multiCMD.egg-info/entry_points.txt +0 -0
  17. {multicmd-1.71 → multicmd-1.72}/multiCMD.egg-info/top_level.txt +0 -0
  18. {multicmd-1.71 → multicmd-1.72}/scripts/multiCMD +0 -0
  19. {multicmd-1.71 → multicmd-1.72}/setup.cfg +0 -0
  20. {multicmd-1.71 → multicmd-1.72}/setup.py +0 -0
  21. {multicmd-1.71 → multicmd-1.72}/tests/test_cli.py +0 -0
  22. {multicmd-1.71 → multicmd-1.72}/tests/test_cli_closed_stdout.py +0 -0
  23. {multicmd-1.71 → multicmd-1.72}/tests/test_cli_failed_stdout.py +0 -0
  24. {multicmd-1.71 → multicmd-1.72}/tests/test_cli_input.py +0 -0
  25. {multicmd-1.71 → multicmd-1.72}/tests/test_cli_summary.py +0 -0
  26. {multicmd-1.71 → multicmd-1.72}/tests/test_display.py +0 -0
  27. {multicmd-1.71 → multicmd-1.72}/tests/test_embed.py +0 -0
  28. {multicmd-1.71 → multicmd-1.72}/tests/test_expand_ranges.py +0 -0
  29. {multicmd-1.71 → multicmd-1.72}/tests/test_handover.py +0 -0
  30. {multicmd-1.71 → multicmd-1.72}/tests/test_helpers.py +0 -0
  31. {multicmd-1.71 → multicmd-1.72}/tests/test_packaging.py +0 -0
  32. {multicmd-1.71 → multicmd-1.72}/tests/test_pass_fds.py +0 -0
  33. {multicmd-1.71 → multicmd-1.72}/tests/test_ping.py +0 -0
  34. {multicmd-1.71 → multicmd-1.72}/tests/test_process_groups.py +0 -0
  35. {multicmd-1.71 → multicmd-1.72}/tests/test_pty.py +0 -0
  36. {multicmd-1.71 → multicmd-1.72}/tests/test_reader.py +0 -0
  37. {multicmd-1.71 → multicmd-1.72}/tests/test_reader_quit.py +0 -0
  38. {multicmd-1.71 → multicmd-1.72}/tests/test_regressions.py +0 -0
  39. {multicmd-1.71 → multicmd-1.72}/tests/test_run_command.py +0 -0
  40. {multicmd-1.71 → multicmd-1.72}/tests/test_run_commands.py +0 -0
  41. {multicmd-1.71 → multicmd-1.72}/tests/test_task.py +0 -0
  42. {multicmd-1.71 → multicmd-1.72}/tests/test_terminal_width.py +0 -0
  43. {multicmd-1.71 → multicmd-1.72}/tests/test_windows.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.71
3
+ Version: 1.72
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -89,8 +89,8 @@ options:
89
89
  = never, the default )
90
90
  -m, --max_threads max_threads
91
91
  maximum number of commands to run at once ( 0 = all )
92
- --sudo use sudo for commands ( sudo -v asks first; on a
93
- terminal they run as sudo -n )
92
+ --sudo use sudo for commands ( sudo -v asks first; they run
93
+ as sudo -n on a terminal, or where sudo -v failed )
94
94
  -q, --quiet quiet mode: hide command output ( the summary still
95
95
  shows )
96
96
  -n, --dry-run print each command, quoted, instead of running it
@@ -157,7 +157,13 @@ mcmd --sudo "systemctl restart myservice"
157
157
  `sudo -v` asks for the password first, on the terminal, when `mcmd` runs in its foreground. Each command then runs as
158
158
  `sudo -n` wherever there is a terminal, so one that sudo would still ask a password for (`timestamp_timeout=0`, a
159
159
  remembered password that ran out mid-run, a run in the background) fails at once with `sudo: a password is required`
160
- instead of waiting at a prompt nobody can answer. With no terminal (cron, `ssh` without `-t`) it runs as plain `sudo`.
160
+ instead of waiting at a prompt nobody can answer. With no terminal (cron, `ssh` without `-t`) `sudo -v` decides: where it
161
+ signs in (NOPASSWD for all, an askpass helper, a sign-in with no question) the commands run as plain `sudo`; where it
162
+ fails, as `sudo -n`, so on sudo 1.8.23, 1.9.5 and 1.9.16 pam_faillock counts at most one failed login per call (one `mcmd`
163
+ run, or one `run_commands` call: the one from `sudo -v`), and sudo 1.9.9 counts each command. Off POSIX there is no
164
+ `sudo -v`: the commands run as plain `sudo`. Where `sudo -v` signs in but a command needs a password
165
+ (every rule NOPASSWD and the command outside them), each refused command still counts one failed login, as before
166
+ ([limitations](docs/limitations.md#where-sudo--v-needs-no-password-but-a-command-does-each-refused-command-counts-as-a-failed-login)).
161
167
 
162
168
  Preview what a range expands to without running anything:
163
169
 
@@ -423,9 +429,10 @@ multiCMD.run_command(["systemctl", "restart", "nginx"])
423
429
  multiCMD.run_command(["id"], use_sudo=True)
424
430
  ```
425
431
 
426
- If `sudo` is not on `PATH`, or you are already root, the request is ignored with
427
- a warning instead of failing. On a terminal the commands run as `sudo -n`, after a `sudo -v` that asks for the password
428
- in the terminal's foreground (as for `mcmd --sudo` above).
432
+ If `sudo` is not on `PATH`, the request is ignored with a warning instead of failing. As root, `set_sudo(True)` (and so
433
+ `mcmd --sudo`) is ignored silently, but `use_sudo=True` on a call still runs `sudo`. On a terminal the commands run as
434
+ `sudo -n`, after a `sudo -v` that asks for the password in the terminal's foreground; with no terminal `sudo -v` decides
435
+ between plain `sudo` and `sudo -n` (as for `mcmd --sudo` above).
429
436
 
430
437
  ## Timeout semantics
431
438
 
@@ -568,6 +575,25 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
568
575
  ```
569
576
 
570
577
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
578
+ `scripts/realsudo.py` runs `--sudo` against real sudo (1.8.23, 1.9.5, 1.9.9, 1.9.16) in Docker, with pam_faillock on, and
579
+ prints a table of what each version of `multiCMD.py` given to it did (`python3 scripts/realsudo.py` says how).
580
+
581
+ ## Upgrading to 1.72 from 1.71
582
+
583
+ - Nothing needs doing. Runs on a terminal, and runs whose `sudo -v` signs in (NOPASSWD for all, an askpass helper, a
584
+ sign-in with no question), are unchanged.
585
+ - Fix: with no terminal (cron, `ssh` without `-t`, mssh), where `sudo -v` fails (a password sudo with nothing remembered),
586
+ each command runs as `sudo -n`, so pam_faillock counts one failed login per call, `sudo -v`'s. 1.71 counted each command
587
+ too: a call of three commands locked the account at `deny=3` (4 records on sudo 1.8.23, 3 on 1.9.5 and 1.9.16). A
588
+ NOPASSWD rule for some commands still runs them. On sudo 1.9.9 (Ubuntu 22.04), which runs PAM for `sudo -n`, each still
589
+ counts.
590
+ - Changed: there `Task.command` and the summary show `sudo -n`, and a refused command says `sudo: a password is required`
591
+ (1.71: `a terminal is required to read the password ...`; on sudo 1.8.23 `no tty present and no askpass program
592
+ specified`). `--dry-run` with no terminal shows plain `sudo`: `sudo -v` does not run in a dry run.
593
+ - Changed, Windows (off POSIX): no `sudo -v` runs; the commands stay plain `sudo` (1.70 and 1.71 ran a `sudo -v` there and
594
+ ignored its exit).
595
+ - Known, planned for 1.73 ([docs/limitations.md](docs/limitations.md)): `AsyncExecutor(max_threads=0)` starts no command,
596
+ and a per-call `max_threads` is ignored while the executor's own semaphore is used (as in 1.70 and 1.71).
571
597
 
572
598
  ## Upgrading to 1.71 from 1.70
573
599
 
@@ -64,8 +64,8 @@ options:
64
64
  = never, the default )
65
65
  -m, --max_threads max_threads
66
66
  maximum number of commands to run at once ( 0 = all )
67
- --sudo use sudo for commands ( sudo -v asks first; on a
68
- terminal they run as sudo -n )
67
+ --sudo use sudo for commands ( sudo -v asks first; they run
68
+ as sudo -n on a terminal, or where sudo -v failed )
69
69
  -q, --quiet quiet mode: hide command output ( the summary still
70
70
  shows )
71
71
  -n, --dry-run print each command, quoted, instead of running it
@@ -132,7 +132,13 @@ mcmd --sudo "systemctl restart myservice"
132
132
  `sudo -v` asks for the password first, on the terminal, when `mcmd` runs in its foreground. Each command then runs as
133
133
  `sudo -n` wherever there is a terminal, so one that sudo would still ask a password for (`timestamp_timeout=0`, a
134
134
  remembered password that ran out mid-run, a run in the background) fails at once with `sudo: a password is required`
135
- instead of waiting at a prompt nobody can answer. With no terminal (cron, `ssh` without `-t`) it runs as plain `sudo`.
135
+ instead of waiting at a prompt nobody can answer. With no terminal (cron, `ssh` without `-t`) `sudo -v` decides: where it
136
+ signs in (NOPASSWD for all, an askpass helper, a sign-in with no question) the commands run as plain `sudo`; where it
137
+ fails, as `sudo -n`, so on sudo 1.8.23, 1.9.5 and 1.9.16 pam_faillock counts at most one failed login per call (one `mcmd`
138
+ run, or one `run_commands` call: the one from `sudo -v`), and sudo 1.9.9 counts each command. Off POSIX there is no
139
+ `sudo -v`: the commands run as plain `sudo`. Where `sudo -v` signs in but a command needs a password
140
+ (every rule NOPASSWD and the command outside them), each refused command still counts one failed login, as before
141
+ ([limitations](docs/limitations.md#where-sudo--v-needs-no-password-but-a-command-does-each-refused-command-counts-as-a-failed-login)).
136
142
 
137
143
  Preview what a range expands to without running anything:
138
144
 
@@ -398,9 +404,10 @@ multiCMD.run_command(["systemctl", "restart", "nginx"])
398
404
  multiCMD.run_command(["id"], use_sudo=True)
399
405
  ```
400
406
 
401
- If `sudo` is not on `PATH`, or you are already root, the request is ignored with
402
- a warning instead of failing. On a terminal the commands run as `sudo -n`, after a `sudo -v` that asks for the password
403
- in the terminal's foreground (as for `mcmd --sudo` above).
407
+ If `sudo` is not on `PATH`, the request is ignored with a warning instead of failing. As root, `set_sudo(True)` (and so
408
+ `mcmd --sudo`) is ignored silently, but `use_sudo=True` on a call still runs `sudo`. On a terminal the commands run as
409
+ `sudo -n`, after a `sudo -v` that asks for the password in the terminal's foreground; with no terminal `sudo -v` decides
410
+ between plain `sudo` and `sudo -n` (as for `mcmd --sudo` above).
404
411
 
405
412
  ## Timeout semantics
406
413
 
@@ -543,6 +550,25 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
543
550
  ```
544
551
 
545
552
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
553
+ `scripts/realsudo.py` runs `--sudo` against real sudo (1.8.23, 1.9.5, 1.9.9, 1.9.16) in Docker, with pam_faillock on, and
554
+ prints a table of what each version of `multiCMD.py` given to it did (`python3 scripts/realsudo.py` says how).
555
+
556
+ ## Upgrading to 1.72 from 1.71
557
+
558
+ - Nothing needs doing. Runs on a terminal, and runs whose `sudo -v` signs in (NOPASSWD for all, an askpass helper, a
559
+ sign-in with no question), are unchanged.
560
+ - Fix: with no terminal (cron, `ssh` without `-t`, mssh), where `sudo -v` fails (a password sudo with nothing remembered),
561
+ each command runs as `sudo -n`, so pam_faillock counts one failed login per call, `sudo -v`'s. 1.71 counted each command
562
+ too: a call of three commands locked the account at `deny=3` (4 records on sudo 1.8.23, 3 on 1.9.5 and 1.9.16). A
563
+ NOPASSWD rule for some commands still runs them. On sudo 1.9.9 (Ubuntu 22.04), which runs PAM for `sudo -n`, each still
564
+ counts.
565
+ - Changed: there `Task.command` and the summary show `sudo -n`, and a refused command says `sudo: a password is required`
566
+ (1.71: `a terminal is required to read the password ...`; on sudo 1.8.23 `no tty present and no askpass program
567
+ specified`). `--dry-run` with no terminal shows plain `sudo`: `sudo -v` does not run in a dry run.
568
+ - Changed, Windows (off POSIX): no `sudo -v` runs; the commands stay plain `sudo` (1.70 and 1.71 ran a `sudo -v` there and
569
+ ignored its exit).
570
+ - Known, planned for 1.73 ([docs/limitations.md](docs/limitations.md)): `AsyncExecutor(max_threads=0)` starts no command,
571
+ and a per-call `max_threads` is ignored while the executor's own semaphore is used (as in 1.70 and 1.71).
546
572
 
547
573
  ## Upgrading to 1.71 from 1.70
548
574
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.71
3
+ Version: 1.72
4
4
  Summary: Run commands simultaneously
5
5
  Home-page: https://github.com/yufei-pan/multiCMD
6
6
  Author: Yufei Pan
@@ -89,8 +89,8 @@ options:
89
89
  = never, the default )
90
90
  -m, --max_threads max_threads
91
91
  maximum number of commands to run at once ( 0 = all )
92
- --sudo use sudo for commands ( sudo -v asks first; on a
93
- terminal they run as sudo -n )
92
+ --sudo use sudo for commands ( sudo -v asks first; they run
93
+ as sudo -n on a terminal, or where sudo -v failed )
94
94
  -q, --quiet quiet mode: hide command output ( the summary still
95
95
  shows )
96
96
  -n, --dry-run print each command, quoted, instead of running it
@@ -157,7 +157,13 @@ mcmd --sudo "systemctl restart myservice"
157
157
  `sudo -v` asks for the password first, on the terminal, when `mcmd` runs in its foreground. Each command then runs as
158
158
  `sudo -n` wherever there is a terminal, so one that sudo would still ask a password for (`timestamp_timeout=0`, a
159
159
  remembered password that ran out mid-run, a run in the background) fails at once with `sudo: a password is required`
160
- instead of waiting at a prompt nobody can answer. With no terminal (cron, `ssh` without `-t`) it runs as plain `sudo`.
160
+ instead of waiting at a prompt nobody can answer. With no terminal (cron, `ssh` without `-t`) `sudo -v` decides: where it
161
+ signs in (NOPASSWD for all, an askpass helper, a sign-in with no question) the commands run as plain `sudo`; where it
162
+ fails, as `sudo -n`, so on sudo 1.8.23, 1.9.5 and 1.9.16 pam_faillock counts at most one failed login per call (one `mcmd`
163
+ run, or one `run_commands` call: the one from `sudo -v`), and sudo 1.9.9 counts each command. Off POSIX there is no
164
+ `sudo -v`: the commands run as plain `sudo`. Where `sudo -v` signs in but a command needs a password
165
+ (every rule NOPASSWD and the command outside them), each refused command still counts one failed login, as before
166
+ ([limitations](docs/limitations.md#where-sudo--v-needs-no-password-but-a-command-does-each-refused-command-counts-as-a-failed-login)).
161
167
 
162
168
  Preview what a range expands to without running anything:
163
169
 
@@ -423,9 +429,10 @@ multiCMD.run_command(["systemctl", "restart", "nginx"])
423
429
  multiCMD.run_command(["id"], use_sudo=True)
424
430
  ```
425
431
 
426
- If `sudo` is not on `PATH`, or you are already root, the request is ignored with
427
- a warning instead of failing. On a terminal the commands run as `sudo -n`, after a `sudo -v` that asks for the password
428
- in the terminal's foreground (as for `mcmd --sudo` above).
432
+ If `sudo` is not on `PATH`, the request is ignored with a warning instead of failing. As root, `set_sudo(True)` (and so
433
+ `mcmd --sudo`) is ignored silently, but `use_sudo=True` on a call still runs `sudo`. On a terminal the commands run as
434
+ `sudo -n`, after a `sudo -v` that asks for the password in the terminal's foreground; with no terminal `sudo -v` decides
435
+ between plain `sudo` and `sudo -n` (as for `mcmd --sudo` above).
429
436
 
430
437
  ## Timeout semantics
431
438
 
@@ -568,6 +575,25 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
568
575
  ```
569
576
 
570
577
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
578
+ `scripts/realsudo.py` runs `--sudo` against real sudo (1.8.23, 1.9.5, 1.9.9, 1.9.16) in Docker, with pam_faillock on, and
579
+ prints a table of what each version of `multiCMD.py` given to it did (`python3 scripts/realsudo.py` says how).
580
+
581
+ ## Upgrading to 1.72 from 1.71
582
+
583
+ - Nothing needs doing. Runs on a terminal, and runs whose `sudo -v` signs in (NOPASSWD for all, an askpass helper, a
584
+ sign-in with no question), are unchanged.
585
+ - Fix: with no terminal (cron, `ssh` without `-t`, mssh), where `sudo -v` fails (a password sudo with nothing remembered),
586
+ each command runs as `sudo -n`, so pam_faillock counts one failed login per call, `sudo -v`'s. 1.71 counted each command
587
+ too: a call of three commands locked the account at `deny=3` (4 records on sudo 1.8.23, 3 on 1.9.5 and 1.9.16). A
588
+ NOPASSWD rule for some commands still runs them. On sudo 1.9.9 (Ubuntu 22.04), which runs PAM for `sudo -n`, each still
589
+ counts.
590
+ - Changed: there `Task.command` and the summary show `sudo -n`, and a refused command says `sudo: a password is required`
591
+ (1.71: `a terminal is required to read the password ...`; on sudo 1.8.23 `no tty present and no askpass program
592
+ specified`). `--dry-run` with no terminal shows plain `sudo`: `sudo -v` does not run in a dry run.
593
+ - Changed, Windows (off POSIX): no `sudo -v` runs; the commands stay plain `sudo` (1.70 and 1.71 ran a `sudo -v` there and
594
+ ignored its exit).
595
+ - Known, planned for 1.73 ([docs/limitations.md](docs/limitations.md)): `AsyncExecutor(max_threads=0)` starts no command,
596
+ and a per-call `max_threads` is ignored while the executor's own semaphore is used (as in 1.70 and 1.71).
571
597
 
572
598
  ## Upgrading to 1.71 from 1.70
573
599
 
@@ -29,9 +29,9 @@ import traceback
29
29
  from pprint import pformat
30
30
 
31
31
  #%% global vars
32
- version = '1.71'
32
+ version = '1.72'
33
33
  __version__ = version
34
- COMMIT_DATE = '2026-11-25'
34
+ COMMIT_DATE = '2026-11-28'
35
35
  # fire-and-forget threads (run_commands with wait_for_return=False) that join_threads() waits on. multiCMD takes no
36
36
  # lock for it: each update is one set operation and each snapshot one set.copy(), as for _live_procs below
37
37
  __running_threads = set()
@@ -787,7 +787,9 @@ class AsyncExecutor:
787
787
  @params:
788
788
  commands: A list of commands to run ( list[str] | list[list[str]] )
789
789
  timeout: The inactivity timeout for each command to override the object default
790
- max_threads: The maximum number of threads to use to override the object default
790
+ max_threads: The call's maximum number of threads ( 0 or less: all at once ), to override the object default. It sizes a
791
+ semaphore only when the call makes its own ( sem=None, or an executor made with semaphore=None ); with the executor's
792
+ own semaphore ( the default ) that one sets the limit, and this only decides whether the call's output counts as concurrent
791
793
  quiet: Whether to suppress output to override the object default
792
794
  dry_run: Whether to simulate running the commands to override the object default
793
795
  parse: Whether to parse ranged input to override the object default
@@ -828,11 +830,12 @@ class AsyncExecutor:
828
830
  extra_env = self.extra_env
829
831
  if pass_fds is ...:
830
832
  pass_fds = self.pass_fds
831
- taskObjects, use_sudo = _build_tasks(commands, parse=parse, shell=shell, env=env, extra_env=extra_env, pass_fds=pass_fds)
833
+ # a call that makes its own semaphore and has a max_threads of the wrong type is refused before _build_tasks runs sudo -v
834
+ unlimited = not sem and max_threads < 1
835
+ taskObjects = _build_tasks(commands, parse=parse, shell=shell, env=env, extra_env=extra_env, pass_fds=pass_fds,
836
+ dry_run=dry_run)
832
837
  if not sem:
833
- sem = threading.Semaphore(max_threads if max_threads >= 1 else max(len(taskObjects), 1))
834
- if use_sudo and not dry_run:
835
- _validate_sudo()
838
+ sem = threading.Semaphore(max(len(taskObjects), 1) if unlimited else max_threads)
836
839
  # the executor's task list keeps growing, so commands count as concurrent whenever max_threads allows it
837
840
  concurrent = max_threads != 1
838
841
  use_color = _resolve_color(color, concurrent)
@@ -1262,7 +1265,7 @@ def set_sudo(use_sudo):
1262
1265
  Set whether to use sudo for commands
1263
1266
 
1264
1267
  @params:
1265
- use_sudo: Whether to use sudo ( on a terminal the commands run as sudo -n: see run_commands )
1268
+ use_sudo: Whether to use sudo ( on a terminal, or where sudo -v failed, the commands run as sudo -n: see run_commands )
1266
1269
 
1267
1270
  @returns:
1268
1271
  None
@@ -2498,13 +2501,14 @@ def _shell_template(template):
2498
2501
  i += 1
2499
2502
  return ''.join(out)
2500
2503
 
2501
- def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, extra_env=None, pass_fds=()):
2504
+ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, extra_env=None, pass_fds=(), dry_run=False):
2502
2505
  '''
2503
2506
  Format commands into Tasks, prefixing sudo when requested and available ( internal )
2504
- env / extra_env / pass_fds ( validated here, before anything runs ) are copied onto every Task
2507
+ env / extra_env / pass_fds ( validated here, before anything runs ) are copied onto every Task. Once they are, sudo -v
2508
+ runs here, unless dry_run ( see _sudo )
2505
2509
 
2506
2510
  @returns:
2507
- tuple[list[Task], bool]: The tasks and whether sudo is used
2511
+ list[Task]: The tasks
2508
2512
  '''
2509
2513
  global USE_SUDO
2510
2514
  global SUDO_PATH
@@ -2521,16 +2525,12 @@ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, ext
2521
2525
  formatedCommands = []
2522
2526
  for command in commands:
2523
2527
  formatedCommands.extend(__format_command(command,expand=parse,shell=shell,variables=variables))
2524
- if use_sudo:
2525
- # a command has a process group of its own, never the terminal's foreground: a sudo there that asks for a password
2526
- # stops for good, or with SIGTTIN ignored ( as mcmd ignores it ) loops. So with a terminal it runs as sudo -n, which
2527
- # fails at once instead ( _validate_sudo asks first, where it can ). With no terminal plain sudo cannot stop: it fails
2528
- # by itself, asks an askpass helper, or signs in with no question ( an ssh agent, Kerberos ), which -n would refuse
2529
- sudo = [SUDO_PATH] if _terminal() is None else [SUDO_PATH, '-n']
2530
- formatedCommands = [sudo + command for command in formatedCommands]
2531
2528
  env = _check_env(env, 'env', drop_empty=True)
2532
2529
  extra_env = _check_env(extra_env, 'extra_env', allow_none=True)
2533
2530
  pass_fds = _check_pass_fds(pass_fds)
2531
+ if use_sudo:
2532
+ sudo = _sudo(dry_run)
2533
+ formatedCommands = [sudo + command for command in formatedCommands]
2534
2534
  # one snapshot shared by every task of the call
2535
2535
  tasks = [Task(command) for command in formatedCommands]
2536
2536
  # a call the main thread makes once the exit hook has begun ( from an atexit handler: see _cut_by_exit )
@@ -2543,7 +2543,7 @@ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, ext
2543
2543
  task._pass_fds = pass_fds
2544
2544
  task._at_exit = at_exit
2545
2545
  task._unread = unread
2546
- return tasks, bool(use_sudo)
2546
+ return tasks
2547
2547
 
2548
2548
  def _terminal():
2549
2549
  '''
@@ -2565,23 +2565,41 @@ def _terminal():
2565
2565
  finally:
2566
2566
  os.close(fd)
2567
2567
 
2568
- def _validate_sudo():
2568
+ def _sudo(dry_run):
2569
+ '''
2570
+ The sudo a call's commands run under, decided once, after sudo -v ( none in a dry run ) ( internal )
2571
+ A command has a process group of its own, never the terminal's foreground, where a sudo that asks for a password stops
2572
+ for good, or with SIGTTIN ignored ( as mcmd ignores it ) loops: so with a terminal it runs as sudo -n, on what sudo -v
2573
+ left remembered. With no terminal plain sudo cannot stop, and can sign in with no person ( an askpass helper, PAM with
2574
+ no question: an ssh agent, Kerberos ), which -n would refuse; but each of its refusals is a failed login to pam_faillock.
2575
+ So there sudo -v decides: where it fails, sudo found no way to sign in without a person ( it asks the same PAM and
2576
+ askpass helper as for a command ), and the commands run as sudo -n, which still runs what a NOPASSWD rule allows and
2577
+ counts no failed login on sudo 1.8.23, 1.9.5 or 1.9.16 ( sudo 1.9.9 runs PAM for -n, and counts each ).
2578
+ Off POSIX ( Windows' own sudo takes neither -v nor -n ) it is plain sudo, and no sudo -v runs.
2579
+ '''
2580
+ if not _IS_POSIX:
2581
+ return [SUDO_PATH]
2582
+ where = _terminal()
2583
+ signed_in = dry_run or _validate_sudo(where)
2584
+ return [SUDO_PATH] if where is None and signed_in else [SUDO_PATH, '-n']
2585
+
2586
+ def _validate_sudo(where):
2569
2587
  '''
2570
- Validate sudo access before running sudo commands ( internal )
2588
+ Run sudo -v before sudo commands, `where` being _terminal()'s answer; whether it signed in ( exits 0 ) ( internal )
2571
2589
  In the terminal's foreground sudo can ask for a password, and what it then remembers for the terminal is what the
2572
2590
  commands ( sudo -n, in process groups of their own, same session ) run on. In a background process group it could only
2573
2591
  stop ( or loop, with SIGTTIN ignored ), so there it runs as sudo -n -v, which asks nothing, and its refusal ( stderr )
2574
2592
  goes nowhere: written to the terminal from a background group under `stty tostop` it stops the whole group ( SIGTTOU )
2575
2593
  until someone brings it to the foreground, and this call waits. Each command reports its own refusal on its own pipes.
2576
- With no terminal it runs as it always has ( an askpass helper, a sign-in with no question ).
2594
+ With no terminal it runs as it always has ( it fails, asks an askpass helper, or signs in with no question ).
2577
2595
  '''
2578
2596
  try:
2579
- if _terminal() is False:
2580
- subprocess.run([SUDO_PATH, '-n', '-v'], stderr=subprocess.DEVNULL)
2581
- else:
2582
- subprocess.run([SUDO_PATH, '-v'])
2597
+ if where is False:
2598
+ return subprocess.run([SUDO_PATH, '-n', '-v'], stderr=subprocess.DEVNULL).returncode == 0
2599
+ return subprocess.run([SUDO_PATH, '-v']).returncode == 0
2583
2600
  except OSError as e:
2584
2601
  _write_error(f'sudo validation failed: {e}')
2602
+ return False
2585
2603
 
2586
2604
  def __format_command(command,expand = False,shell = False,variables = None):
2587
2605
  '''
@@ -2770,7 +2788,8 @@ def run_command(command, timeout=0,max_threads=1,quiet=False,dry_run=False,with_
2770
2788
  wait_for_return: Whether to wait for the return of the command
2771
2789
  sem: The semaphore to use for threading
2772
2790
  use_sudo: Whether to use sudo for commands. On a terminal each runs as sudo -n, so one that sudo would ask a password
2773
- for fails at once ( 'sudo: a password is required' ); sudo -v asks for it first, in the terminal's foreground only
2791
+ for fails at once ( 'sudo: a password is required' ); sudo -v asks for it first, in the terminal's foreground only.
2792
+ With no terminal each runs as plain sudo where sudo -v signed in, as sudo -n where it failed ( off POSIX: plain sudo, no sudo -v )
2774
2793
  raise_error: Whether to raise an error if the command fails
2775
2794
  prefix: Whether to prefix output lines with [#] when commands run at once ( never for one command )
2776
2795
  color: Whether to color output lines ( None: when commands run at once on a terminal without NO_COLOR )
@@ -2827,7 +2846,8 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2827
2846
  wait_for_return: Whether to wait for the return of the commands
2828
2847
  sem: The semaphore to use for threading
2829
2848
  use_sudo: Whether to use sudo for commands. On a terminal each runs as sudo -n, so one that sudo would ask a password
2830
- for fails at once ( 'sudo: a password is required' ); sudo -v asks for it first, in the terminal's foreground only
2849
+ for fails at once ( 'sudo: a password is required' ); sudo -v asks for it first, in the terminal's foreground only.
2850
+ With no terminal each runs as plain sudo where sudo -v signed in, as sudo -n where it failed ( off POSIX: plain sudo, no sudo -v )
2831
2851
  raise_error: Whether to raise an error if the command fails
2832
2852
  prefix: Whether to prefix output lines with [#], the command's 1-based position, when commands run at once
2833
2853
  color: Whether to color output lines per command ( None: when commands run at once on a terminal without NO_COLOR )
@@ -2851,9 +2871,12 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2851
2871
  list: The output of the commands ( list[None] | list[int] | list[list[str]] | list[Task] | None )
2852
2872
  '''
2853
2873
  # initialize the tasks
2854
- tasks, use_sudo = _build_tasks(commands, parse=parse, use_sudo=use_sudo, shell=shell, env=env, extra_env=extra_env, pass_fds=pass_fds)
2874
+ # a call refused for its max_threads ( the wrong type ) runs no sudo -v, so it is checked before _build_tasks
2875
+ unlimited = max_threads < 1
2876
+ tasks = _build_tasks(commands, parse=parse, use_sudo=use_sudo, shell=shell, env=env, extra_env=extra_env, pass_fds=pass_fds,
2877
+ dry_run=dry_run)
2855
2878
  # run the tasks with max_threads. if max_threads is 0, use the number of commands
2856
- if max_threads < 1:
2879
+ if unlimited:
2857
2880
  max_threads = len(tasks)
2858
2881
  # concurrent runs get [#] prefixes ( when asked ) and colors ( on a terminal )
2859
2882
  concurrent = len(tasks) > 1 and max_threads != 1
@@ -2863,8 +2886,6 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2863
2886
  use_pty = _resolve_pty(pty)
2864
2887
  if not sem:
2865
2888
  sem = threading.Semaphore(max_threads) # Limit concurrent sessions
2866
- if use_sudo and not dry_run:
2867
- _validate_sudo()
2868
2889
  if dry_run:
2869
2890
  # nothing runs: show each command once, quoted so it can be pasted into a shell
2870
2891
  for task in tasks:
@@ -3221,7 +3242,7 @@ def _run_cli():
3221
3242
  parser.add_argument('-p','--parse', action='store_true',help='Parse ranged input and expand them into multiple commands')
3222
3243
  parser.add_argument('-t','--timeout', metavar='SECONDS', type=float, default=0,help='kill a command after SECONDS with no output at all ( 0 = never, the default )')
3223
3244
  parser.add_argument('-m','--max_threads', metavar='max_threads', type=int, default=1,help='maximum number of commands to run at once ( 0 = all )')
3224
- parser.add_argument('--sudo', action='store_true',help='use sudo for commands ( sudo -v asks first; on a terminal they run as sudo -n )')
3245
+ parser.add_argument('--sudo', action='store_true',help='use sudo for commands ( sudo -v asks first; they run as sudo -n on a terminal, or where sudo -v failed )')
3225
3246
  parser.add_argument('-q','--quiet', action='store_true',help='quiet mode: hide command output ( the summary still shows )')
3226
3247
  parser.add_argument('-n','--dry-run', action='store_true',help='print each command, quoted, instead of running it')
3227
3248
  parser.add_argument('--shell', action='store_true',help='run each command through /bin/sh -c ( pipes, ;, > and globs work )')
@@ -18,11 +18,16 @@ def test_dry_run_skips_sudo_validation(monkeypatch, capsys):
18
18
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
19
19
  # ( no terminal: with one the prefix is sudo -n, see test_sudo.py )
20
20
  monkeypatch.setattr(multiCMD, '_terminal', lambda: None)
21
- def fail():
21
+ def fail(where):
22
22
  raise AssertionError('sudo -v must not run in a dry run')
23
23
  monkeypatch.setattr(multiCMD, '_validate_sudo', fail)
24
+ # ( with no terminal it shows what runs where sudo -v signs in )
24
25
  run_commands([['id']], dry_run=True, use_sudo=True)
25
26
  assert capsys.readouterr().out == '/usr/bin/sudo id\n'
27
+ multiCMD.USE_SUDO = True
28
+ executor = multiCMD.AsyncExecutor(dry_run=True)
29
+ assert [task.command for task in executor.run_commands([['id']])] == [['/usr/bin/sudo', 'id']]
30
+ assert executor.wait(10) == []
26
31
 
27
32
 
28
33
  def test_dry_run_tasks_are_not_failures():
@@ -24,6 +24,22 @@ def test_executor_run_wait_results_codes():
24
24
  assert ex.get_results() == [["a"], ["b"], []]
25
25
 
26
26
 
27
+ def test_a_call_without_a_semaphore_takes_max_threads_0_as_all_at_once(tmp_path):
28
+ # the executor's own semaphore holds max_threads; a call that brings none gets one the size of the call, for 0 ( a
29
+ # semaphore of 0 would start nothing ). Each command makes its marker, then waits up to 10 s for all three markers:
30
+ # started one at a time, the first two time out ( exit 1 ), so only commands that overlap all exit 0
31
+ script = ('touch "$1"; i=0; while [ "$(ls "$2" | wc -l)" -lt 3 ] && [ "$i" -lt 200 ]; do sleep 0.05; i=$((i+1)); done; '
32
+ '[ "$(ls "$2" | wc -l)" -eq 3 ]')
33
+ ex = AsyncExecutor(max_threads=1, quiet=True)
34
+ try:
35
+ ex.run_commands([["sh", "-c", script, "sh", str(tmp_path / str(n)), str(tmp_path)] for n in range(3)],
36
+ max_threads=0, sem=None)
37
+ assert ex.wait(timeout=30) == []
38
+ assert ex.get_return_codes() == [0, 0, 0]
39
+ finally:
40
+ ex.stop(timeout=5)
41
+
42
+
27
43
  @pytest.mark.slow
28
44
  def test_executor_join_prints_errors(capsys):
29
45
  ex = AsyncExecutor(max_threads=1, quiet=True)
@@ -604,7 +620,7 @@ def test_ctrl_c_while_fire_and_forget_threads_start(monkeypatch, after):
604
620
  real_build = multiCMD._build_tasks
605
621
  def build(*args, **kwargs):
606
622
  built = real_build(*args, **kwargs)
607
- tasks.extend(built[0])
623
+ tasks.extend(built)
608
624
  return built
609
625
  monkeypatch.setattr(multiCMD, '_build_tasks', build)
610
626
  # ( the first thread got to its target before the second start fails, see _fail_nth_start )
@@ -298,7 +298,7 @@ def test_child_env_survives_other_threads_changing_os_environ():
298
298
  def test_empty_extra_env_is_no_extra_env():
299
299
  assert multiCMD._check_env({}, 'extra_env', allow_none=True) is None
300
300
  assert multiCMD._check_env({}, 'env') == {}
301
- tasks, _ = multiCMD._build_tasks([['true']], extra_env={})
301
+ tasks = multiCMD._build_tasks([['true']], extra_env={})
302
302
  assert tasks[0]._extra_env is None
303
303
  assert multiCMD._child_env(tasks[0]) is None
304
304
 
@@ -354,7 +354,7 @@ def test_windows_names_are_case_insensitive_and_may_start_with_equals():
354
354
 
355
355
  def test_an_environment_is_checked_and_copied_once_per_call():
356
356
  env = multiCMD._check_env({'PATH': os.environ['PATH']}, 'env')
357
- tasks, _ = multiCMD._build_tasks([['true'], ['true']], env=env, extra_env={'A': None})
357
+ tasks = multiCMD._build_tasks([['true'], ['true']], env=env, extra_env={'A': None})
358
358
  assert tasks[0]._env is tasks[1]._env
359
359
  assert tasks[0]._extra_env is tasks[1]._extra_env
360
360
  assert tasks[0]._extra_env['A'] is None
@@ -659,7 +659,7 @@ def test_snapshots_are_dropped_whatever_happens_to_the_task(launcher, tmp_path,
659
659
  assert dry._env is None and dry._extra_env is None
660
660
  failing = run_command(['/no/such/cmd'], quiet=True, extra_env={'A': '1'}, return_object=True)
661
661
  assert failing._extra_env is None and failing._env is None
662
- tasks, _ = multiCMD._build_tasks([['true']], env={'PATH': '/bin'}, extra_env={'A': '1'})
662
+ tasks = multiCMD._build_tasks([['true']], env={'PATH': '/bin'}, extra_env={'A': '1'})
663
663
  tasks[0].stop = True
664
664
  multiCMD.__dict__['__run_command'](tasks[0], threading.Semaphore(1), quiet=True)
665
665
  assert tasks[0]._env is None and tasks[0]._extra_env is None
@@ -936,7 +936,7 @@ def test_an_interpreter_that_cannot_run_is_an_internal_error(launcher, tmp_path,
936
936
  # ---- a snapshot can be copied and pickled
937
937
 
938
938
  def test_a_task_still_holding_its_snapshot_can_be_copied_and_pickled():
939
- tasks, _ = multiCMD._build_tasks([['true']], env={'PATH': '/bin'}, extra_env={'A': None, 'B': '1'})
939
+ tasks = multiCMD._build_tasks([['true']], env={'PATH': '/bin'}, extra_env={'A': None, 'B': '1'})
940
940
  for clone in (copy.deepcopy(tasks[0]), pickle.loads(pickle.dumps(tasks[0])), copy.copy(tasks[0])):
941
941
  assert clone._env == {'PATH': '/bin'} and clone._extra_env == {'A': None, 'B': '1'}
942
942
  with pytest.raises(TypeError):
@@ -345,7 +345,7 @@ def _builds(monkeypatch):
345
345
  '''The tasks every run_commands() call builds, in a list'''
346
346
  tasks = []
347
347
  real_build = multiCMD._build_tasks
348
- monkeypatch.setattr(multiCMD, '_build_tasks', lambda *a, **k: (lambda built: (tasks.extend(built[0]), built)[1])(real_build(*a, **k)))
348
+ monkeypatch.setattr(multiCMD, '_build_tasks', lambda *a, **k: (lambda built: (tasks.extend(built), built)[1])(real_build(*a, **k)))
349
349
  return tasks
350
350
 
351
351
 
@@ -10,7 +10,7 @@ def test_string_commands_follow_shell_quoting():
10
10
 
11
11
 
12
12
  def test_simple_strings_split_as_before():
13
- tasks, _ = multiCMD._build_tasks(['lsblk -b -n -p -o NAME,SIZE -P', 'ping -c 1 host1'])
13
+ tasks = multiCMD._build_tasks(['lsblk -b -n -p -o NAME,SIZE -P', 'ping -c 1 host1'])
14
14
  assert [task.command for task in tasks] == [
15
15
  ['lsblk', '-b', '-n', '-p', '-o', 'NAME,SIZE', '-P'],
16
16
  ['ping', '-c', '1', 'host1'],
@@ -36,8 +36,8 @@ def test_shell_mode_with_sudo_wraps_the_shell(monkeypatch):
36
36
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
37
37
  # ( no terminal: with one the prefix is sudo -n, see test_sudo.py )
38
38
  monkeypatch.setattr(multiCMD, '_terminal', lambda: None)
39
- tasks, used = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
40
- assert used is True
39
+ monkeypatch.setattr(multiCMD, '_validate_sudo', lambda where: True)
40
+ tasks = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
41
41
  assert tasks[0].command == ['/usr/bin/sudo', '/bin/sh', '-c', 'echo hi']
42
42
 
43
43
 
@@ -80,7 +80,7 @@ def test_ctrl_c_in_a_pool_waits_for_a_command_slow_to_die(monkeypatch):
80
80
  real = multiCMD._build_tasks
81
81
  def build(*args, **kwargs):
82
82
  built = real(*args, **kwargs)
83
- tasks.extend(built[0])
83
+ tasks.extend(built)
84
84
  return built
85
85
  monkeypatch.setattr(multiCMD, '_build_tasks', build)
86
86
  start = time.monotonic()
@@ -104,7 +104,7 @@ def test_a_finished_pool_task_does_not_report_its_worker(monkeypatch):
104
104
  real_build = multiCMD._build_tasks
105
105
  def build(*args, **kwargs):
106
106
  built = real_build(*args, **kwargs)
107
- first.append(built[0][0])
107
+ first.append(built[0])
108
108
  return built
109
109
  monkeypatch.setattr(multiCMD, '__run_command', run)
110
110
  monkeypatch.setattr(multiCMD, '_build_tasks', build)
@@ -155,7 +155,7 @@ def _record_tasks(monkeypatch):
155
155
  real = multiCMD._build_tasks
156
156
  def build(*args, **kwargs):
157
157
  built = real(*args, **kwargs)
158
- tasks.extend(built[0])
158
+ tasks.extend(built)
159
159
  return built
160
160
  monkeypatch.setattr(multiCMD, '_build_tasks', build)
161
161
  return tasks
@@ -49,48 +49,141 @@ def test_use_sudo_none_path_does_not_crash():
49
49
 
50
50
 
51
51
  # 1.71: on a terminal a command's sudo runs as sudo -n ( it is never in the terminal's foreground ), and sudo -v asks only
52
- # in the foreground; with no terminal both run as before. None / True / False: _terminal()'s answers
53
-
54
- @pytest.mark.parametrize('where, prefix', [(None, ['/usr/bin/sudo']), (True, ['/usr/bin/sudo', '-n']),
55
- (False, ['/usr/bin/sudo', '-n'])])
56
- def test_sudo_prefix_is_sudo_n_wherever_there_is_a_terminal(monkeypatch, where, prefix):
52
+ # in the foreground. 1.72: with no terminal sudo -v decides: plain sudo where it signed in, sudo -n where it failed ( so
53
+ # on sudo 1.8.23, 1.9.5 and 1.9.16 pam_faillock counts one failed login per call, not one per command; 1.9.9 runs PAM for
54
+ # sudo -n too, and counts each ). None / True / False: _terminal()'s answers
55
+
56
+ @pytest.mark.parametrize('where, signed_in, prefix', [(None, True, ['/usr/bin/sudo']), (None, False, ['/usr/bin/sudo', '-n']),
57
+ (True, True, ['/usr/bin/sudo', '-n']), (True, False, ['/usr/bin/sudo', '-n']),
58
+ (False, True, ['/usr/bin/sudo', '-n']), (False, False, ['/usr/bin/sudo', '-n'])])
59
+ def test_sudo_prefix_is_sudo_n_on_a_terminal_or_once_sudo_v_failed(monkeypatch, where, signed_in, prefix):
60
+ asked = []
57
61
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
58
62
  monkeypatch.setattr(multiCMD, '_terminal', lambda: where)
59
- tasks, used = multiCMD._build_tasks([['id', '-u'], 'echo hi'], use_sudo=True)
60
- assert used is True
63
+ monkeypatch.setattr(multiCMD, '_validate_sudo', lambda where: asked.append(where) or signed_in)
64
+ tasks = multiCMD._build_tasks([['id', '-u'], 'echo hi'], use_sudo=True)
61
65
  assert [task.command for task in tasks] == [prefix + ['id', '-u'], prefix + ['echo', 'hi']]
66
+ # sudo -v ran once, told where it runs
67
+ assert asked == [where]
62
68
  # shell mode wraps the shell, and set_sudo's global takes the same prefix
63
- tasks, _ = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
69
+ tasks = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
64
70
  assert tasks[0].command == prefix + ['/bin/sh', '-c', 'echo hi']
65
71
  multiCMD.USE_SUDO = True
66
- tasks, _ = multiCMD._build_tasks(['id'])
72
+ tasks = multiCMD._build_tasks(['id'])
67
73
  assert tasks[0].command == prefix + ['id']
74
+ assert asked == [where] * 3
75
+
76
+
77
+ def test_one_answer_of_the_terminal_decides_both_sudo_v_and_the_prefix(monkeypatch):
78
+ # the terminal is asked once per call: were sudo -v told "none" ( so it may sign in for plain sudo ) and the prefix
79
+ # decided on a second answer, the two could disagree
80
+ answers = [None, True]
81
+ asked = []
82
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
83
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: answers.pop(0))
84
+ monkeypatch.setattr(multiCMD, '_validate_sudo', lambda where: asked.append(where) or True)
85
+ tasks = multiCMD._build_tasks([['id']], use_sudo=True)
86
+ assert (asked, tasks[0].command, answers) == ([None], ['/usr/bin/sudo', 'id'], [True])
87
+
88
+
89
+ def test_sudo_v_runs_once_the_arguments_are_checked(monkeypatch):
90
+ # a call refused for its command, env, extra_env, pass_fds or max_threads runs nothing, sudo -v included ( on a terminal
91
+ # it would ask for a password first )
92
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
93
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: None)
94
+ def fail(where):
95
+ raise AssertionError('sudo -v ran for a call that is refused')
96
+ monkeypatch.setattr(multiCMD, '_validate_sudo', fail)
97
+ with pytest.raises(ValueError):
98
+ multiCMD.run_commands([['id']], use_sudo=True, extra_env={'': '1'})
99
+ with pytest.raises(ValueError):
100
+ multiCMD.run_commands([['id']], use_sudo=True, env={'A=B': '1'}, quiet=True)
101
+ multiCMD.USE_SUDO = True
102
+ with pytest.raises(ValueError, match='cannot parse command'):
103
+ multiCMD.run_commands(["echo 'oops"], use_sudo=True, quiet=True)
104
+ with pytest.raises(ValueError):
105
+ multiCMD.AsyncExecutor().run_commands([['id']], pass_fds=(-1,))
106
+ # a max_threads that cannot be compared with a number ( None, a string ) raises before it too, as in 1.71 ( the
107
+ # executor reads it only to make a semaphore, so only for a call that brings none: sem=None )
108
+ for max_threads in (None, '2'):
109
+ with pytest.raises(TypeError):
110
+ multiCMD.run_commands([['id']], use_sudo=True, max_threads=max_threads, quiet=True)
111
+ with pytest.raises(TypeError):
112
+ multiCMD.AsyncExecutor().run_commands([['id']], max_threads=max_threads, sem=None, quiet=True)
113
+
114
+
115
+ @pytest.mark.parametrize('signed_in', [True, False])
116
+ def test_off_posix_sudo_stays_plain_and_runs_no_sudo_v(monkeypatch, signed_in):
117
+ # Windows' own sudo takes neither -v nor -n ( 1.70 and 1.71 ran plain sudo there ): no sudo -v, whatever it would answer
118
+ monkeypatch.setattr(multiCMD, '_IS_POSIX', False)
119
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', 'C:/sudo.exe')
120
+ asked = []
121
+ monkeypatch.setattr(multiCMD, '_validate_sudo', lambda where: asked.append(where) or signed_in)
122
+ assert multiCMD._build_tasks([['id']], use_sudo=True)[0].command == ['C:/sudo.exe', 'id']
123
+ assert multiCMD._build_tasks([['id']], use_sudo=True, dry_run=True)[0].command == ['C:/sudo.exe', 'id']
124
+ assert asked == []
68
125
 
69
126
 
70
127
  def test_no_sudo_asks_nothing_of_the_terminal(monkeypatch):
71
128
  def fail():
72
129
  raise AssertionError('the terminal is looked at only for sudo')
73
130
  monkeypatch.setattr(multiCMD, '_terminal', fail)
74
- tasks, used = multiCMD._build_tasks(['id'])
75
- assert used is False and tasks[0].command == ['id']
131
+ tasks = multiCMD._build_tasks(['id'])
132
+ assert tasks[0].command == ['id']
76
133
 
77
134
 
78
135
  # the background one writes its refusal nowhere ( stderr to /dev/null ): to the terminal, under `stty tostop`, it stops the
79
- # process group; the others keep sudo's own stderr, which is what an operator reads of a failed sign-in
136
+ # process group; the others keep sudo's own stderr, which is what an operator reads of a failed sign-in. It answers
137
+ # whether sudo -v signed in, by its exit
80
138
  @pytest.mark.parametrize('where, argv, kwargs', [(None, ['/usr/bin/sudo', '-v'], {}), (True, ['/usr/bin/sudo', '-v'], {}),
81
139
  (False, ['/usr/bin/sudo', '-n', '-v'], {'stderr': subprocess.DEVNULL})])
82
- def test_sudo_v_asks_only_in_the_terminals_foreground(monkeypatch, where, argv, kwargs):
140
+ @pytest.mark.parametrize('returncode, signed_in', [(0, True), (1, False)])
141
+ def test_sudo_v_asks_only_in_the_terminals_foreground(monkeypatch, where, argv, kwargs, returncode, signed_in):
83
142
  calls = []
84
143
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
85
- monkeypatch.setattr(multiCMD, '_terminal', lambda: where)
86
- monkeypatch.setattr(multiCMD.subprocess, 'run', lambda *args, **kwargs: calls.append((args, kwargs)))
87
- multiCMD._validate_sudo()
144
+ def run(*args, **kwargs):
145
+ calls.append((args, kwargs))
146
+ return subprocess.CompletedProcess(args[0], returncode)
147
+ monkeypatch.setattr(multiCMD.subprocess, 'run', run)
148
+ assert multiCMD._validate_sudo(where) is signed_in
88
149
  assert calls == [((argv,), kwargs)]
89
150
 
90
151
 
91
- def test_dry_run_shows_sudo_n_on_a_terminal(monkeypatch, capsys):
152
+ def test_sudo_v_that_cannot_start_has_not_signed_in(monkeypatch, capsys):
153
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/no/such/sudo')
154
+ assert multiCMD._validate_sudo(None) is False
155
+ assert 'sudo validation failed' in capsys.readouterr().err
156
+
157
+
158
+ # with no terminal ( cron, ssh without -t ), through the library, with a stand-in sudo that logs its arguments: where its
159
+ # sudo -v fails, each command runs as sudo -n; where it signs in, as plain sudo
160
+ _NO_TERMINAL_PROBE = r'''
161
+ import sys
162
+ sys.path.insert(0, sys.argv[1])
163
+ import multiCMD
164
+ multiCMD.SUDO_PATH = sys.argv[2]
165
+ tasks = multiCMD.run_commands([['id', '-u'], ['true']], quiet=True, use_sudo=True, return_object=True)
166
+ print(multiCMD._terminal(), [task.returncode for task in tasks])
167
+ '''
168
+
169
+
170
+ @pytest.mark.skipif(os.name != 'posix', reason='a controlling terminal is POSIX only')
171
+ @pytest.mark.parametrize('validates, expected', [(0, ['-v', 'id -u', 'true']), (1, ['-v', '-n id -u', '-n true'])])
172
+ def test_with_no_terminal_sudo_v_decides_the_prefix(tmp_path, validates, expected):
173
+ log = tmp_path / 'sudo.log'
174
+ sudo = tmp_path / 'sudo'
175
+ sudo.write_text('#!/bin/sh\necho "$*" >> %s\n[ "$1" = -v ] && exit %d\nexit 0\n' % (log, validates))
176
+ sudo.chmod(0o755)
177
+ proc = subprocess.run([sys.executable, '-c', _NO_TERMINAL_PROBE, str(PACKAGE_ROOT), str(sudo)], stdin=subprocess.DEVNULL,
178
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, universal_newlines=True, timeout=60)
179
+ assert (proc.stdout, proc.stderr) == ('None [0, 0]\n', '')
180
+ assert log.read_text().splitlines() == expected
181
+
182
+
183
+ @pytest.mark.parametrize('where', [True, False], ids=['foreground', 'background'])
184
+ def test_dry_run_shows_sudo_n_on_a_terminal(monkeypatch, capsys, where):
92
185
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
93
- monkeypatch.setattr(multiCMD, '_terminal', lambda: True)
186
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: where)
94
187
  multiCMD.run_commands([['id']], dry_run=True, use_sudo=True)
95
188
  assert capsys.readouterr().out == '/usr/bin/sudo -n id\n'
96
189
 
@@ -142,9 +142,8 @@ def test_sudo_validation_runs_in_the_foreground(monkeypatch):
142
142
  calls = []
143
143
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
144
144
  # ( in the terminal's foreground: elsewhere see test_sudo.py )
145
- monkeypatch.setattr(multiCMD, '_terminal', lambda: True)
146
- monkeypatch.setattr(subprocess, 'run', lambda *args, **kwargs: calls.append((args, kwargs)))
147
- multiCMD._validate_sudo()
145
+ monkeypatch.setattr(subprocess, 'run', lambda *args, **kwargs: calls.append((args, kwargs)) or subprocess.CompletedProcess(args[0], 0))
146
+ assert multiCMD._validate_sudo(True) is True
148
147
  assert calls == [((['/usr/bin/sudo', '-v'],), {})]
149
148
 
150
149
 
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes