multiCMD 1.70__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 (44) hide show
  1. {multicmd-1.70 → multicmd-1.72}/PKG-INFO +61 -7
  2. {multicmd-1.70 → multicmd-1.72}/README.md +60 -6
  3. {multicmd-1.70 → multicmd-1.72}/multiCMD.egg-info/PKG-INFO +61 -7
  4. {multicmd-1.70 → multicmd-1.72}/multiCMD.py +82 -27
  5. {multicmd-1.70 → multicmd-1.72}/tests/test_api.py +8 -1
  6. {multicmd-1.70 → multicmd-1.72}/tests/test_async_executor.py +17 -1
  7. {multicmd-1.70 → multicmd-1.72}/tests/test_env.py +4 -4
  8. {multicmd-1.70 → multicmd-1.72}/tests/test_interrupts.py +1 -1
  9. {multicmd-1.70 → multicmd-1.72}/tests/test_parsing.py +5 -3
  10. {multicmd-1.70 → multicmd-1.72}/tests/test_pool.py +3 -3
  11. multicmd-1.72/tests/test_sudo.py +338 -0
  12. {multicmd-1.70 → multicmd-1.72}/tests/test_supervision.py +3 -2
  13. multicmd-1.70/tests/test_sudo.py +0 -45
  14. {multicmd-1.70 → multicmd-1.72}/LICENSE +0 -0
  15. {multicmd-1.70 → multicmd-1.72}/multiCMD.egg-info/SOURCES.txt +0 -0
  16. {multicmd-1.70 → multicmd-1.72}/multiCMD.egg-info/dependency_links.txt +0 -0
  17. {multicmd-1.70 → multicmd-1.72}/multiCMD.egg-info/entry_points.txt +0 -0
  18. {multicmd-1.70 → multicmd-1.72}/multiCMD.egg-info/top_level.txt +0 -0
  19. {multicmd-1.70 → multicmd-1.72}/scripts/multiCMD +0 -0
  20. {multicmd-1.70 → multicmd-1.72}/setup.cfg +0 -0
  21. {multicmd-1.70 → multicmd-1.72}/setup.py +0 -0
  22. {multicmd-1.70 → multicmd-1.72}/tests/test_cli.py +0 -0
  23. {multicmd-1.70 → multicmd-1.72}/tests/test_cli_closed_stdout.py +0 -0
  24. {multicmd-1.70 → multicmd-1.72}/tests/test_cli_failed_stdout.py +0 -0
  25. {multicmd-1.70 → multicmd-1.72}/tests/test_cli_input.py +0 -0
  26. {multicmd-1.70 → multicmd-1.72}/tests/test_cli_summary.py +0 -0
  27. {multicmd-1.70 → multicmd-1.72}/tests/test_display.py +0 -0
  28. {multicmd-1.70 → multicmd-1.72}/tests/test_embed.py +0 -0
  29. {multicmd-1.70 → multicmd-1.72}/tests/test_expand_ranges.py +0 -0
  30. {multicmd-1.70 → multicmd-1.72}/tests/test_handover.py +0 -0
  31. {multicmd-1.70 → multicmd-1.72}/tests/test_helpers.py +0 -0
  32. {multicmd-1.70 → multicmd-1.72}/tests/test_packaging.py +0 -0
  33. {multicmd-1.70 → multicmd-1.72}/tests/test_pass_fds.py +0 -0
  34. {multicmd-1.70 → multicmd-1.72}/tests/test_ping.py +0 -0
  35. {multicmd-1.70 → multicmd-1.72}/tests/test_process_groups.py +0 -0
  36. {multicmd-1.70 → multicmd-1.72}/tests/test_pty.py +0 -0
  37. {multicmd-1.70 → multicmd-1.72}/tests/test_reader.py +0 -0
  38. {multicmd-1.70 → multicmd-1.72}/tests/test_reader_quit.py +0 -0
  39. {multicmd-1.70 → multicmd-1.72}/tests/test_regressions.py +0 -0
  40. {multicmd-1.70 → multicmd-1.72}/tests/test_run_command.py +0 -0
  41. {multicmd-1.70 → multicmd-1.72}/tests/test_run_commands.py +0 -0
  42. {multicmd-1.70 → multicmd-1.72}/tests/test_task.py +0 -0
  43. {multicmd-1.70 → multicmd-1.72}/tests/test_terminal_width.py +0 -0
  44. {multicmd-1.70 → 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.70
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,7 +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
92
+ --sudo use sudo for commands ( sudo -v asks first; they run
93
+ as sudo -n on a terminal, or where sudo -v failed )
93
94
  -q, --quiet quiet mode: hide command output ( the summary still
94
95
  shows )
95
96
  -n, --dry-run print each command, quoted, instead of running it
@@ -153,6 +154,17 @@ Run with `sudo` (falls back gracefully if `sudo` is unavailable or you are alrea
153
154
  mcmd --sudo "systemctl restart myservice"
154
155
  ```
155
156
 
157
+ `sudo -v` asks for the password first, on the terminal, when `mcmd` runs in its foreground. Each command then runs as
158
+ `sudo -n` wherever there is a terminal, so one that sudo would still ask a password for (`timestamp_timeout=0`, a
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`) `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)).
167
+
156
168
  Preview what a range expands to without running anything:
157
169
 
158
170
  ```bash
@@ -417,8 +429,10 @@ multiCMD.run_command(["systemctl", "restart", "nginx"])
417
429
  multiCMD.run_command(["id"], use_sudo=True)
418
430
  ```
419
431
 
420
- If `sudo` is not on `PATH`, or you are already root, the request is ignored with
421
- a warning instead of failing.
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).
422
436
 
423
437
  ## Timeout semantics
424
438
 
@@ -435,9 +449,11 @@ default, in the API and on the command line) disables it.
435
449
 
436
450
  Every command runs in a process group of its own, so a timeout, `stop()` or Ctrl-C reaches the
437
451
  whole process tree, not just the first process. On Python 3.11+ this uses `Popen(process_group=0)`;
438
- older Pythons start the command through a tiny exec wrapper. A command that reads the terminal (a
439
- password prompt, for example) fails at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for
440
- it, and `mcmd` also ignores them, which every command inherits through any shell.
452
+ older Pythons start the command through a tiny exec wrapper. A command that reads the terminal fails
453
+ at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for it, and `mcmd` also ignores them,
454
+ which every command inherits through any shell. A `sudo` of your own inside a command is the
455
+ exception: it stops, or under `mcmd` prints its prompt over and over, until a Ctrl-C. Use `--sudo` /
456
+ `use_sudo`, or run `sudo -v` first.
441
457
 
442
458
  Signals sent to your program's group do not reach the commands, so multiCMD stops them itself. One
443
459
  Ctrl-C (or a SIGTERM handler's `sys.exit()`) in a call waiting on the main thread, `join_threads()`
@@ -559,6 +575,44 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
559
575
  ```
560
576
 
561
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).
597
+
598
+ ## Upgrading to 1.71 from 1.70
599
+
600
+ - Nothing needs doing for a run in the foreground of a terminal whose sudo remembers the password between commands (the
601
+ default), for NOPASSWD rules, or with no terminal (cron, `ssh` without `-t`): those run as before.
602
+ - Fix: with `--sudo` / `use_sudo` on a terminal each command runs as `sudo -n`, so one that sudo would ask a password for
603
+ at that moment (`timestamp_timeout=0`, or the remembered password ran out mid-run) fails at once with
604
+ `sudo: a password is required`. 1.70 waited at sudo's prompt until a Ctrl-C (a password typed there showed on the
605
+ screen), or under `mcmd` printed the prompt over and over, or failed after a failed login that pam_faillock counted.
606
+ `Task.command` and `--dry-run` show the `-n`.
607
+ - Fix: `sudo -v` asks for the password only where multiCMD is in its terminal's foreground. In a background job
608
+ (`mcmd --sudo ... &`), under another `mcmd`, or under a script's `timeout` (without `--foreground`) it runs as `sudo -n -v` and asks nothing, so a run with nothing
609
+ remembered fails at once. 1.70 hung there (a program using the library as a background job stopped until `fg`), and a
610
+ password typed at the prompt went to the shell. Run `sudo -v` first, or run in the foreground.
611
+ - Changed: on a terminal, a sudo that signs in with no question (an ssh agent through pam_ssh_agent_auth, Kerberos) and
612
+ remembers nothing at that moment is refused where 1.70 ran the command: with `timestamp_timeout=0`, once the remembered
613
+ sign-in ran out mid-run, and in the background or under another `mcmd` when no `sudo -v` ran first. Give the commands
614
+ NOPASSWD. `Defaults noninteractive_auth` (sudo 1.9.10 and later) lets `sudo -n` sign in with no question, but then
615
+ pam_faillock counts each refusal of a password sudo as a failed login; sudo 1.9.9 (Ubuntu 22.04) does both by default.
562
616
 
563
617
  ## Upgrading to 1.70 from 1.69
564
618
 
@@ -64,7 +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
67
+ --sudo use sudo for commands ( sudo -v asks first; they run
68
+ as sudo -n on a terminal, or where sudo -v failed )
68
69
  -q, --quiet quiet mode: hide command output ( the summary still
69
70
  shows )
70
71
  -n, --dry-run print each command, quoted, instead of running it
@@ -128,6 +129,17 @@ Run with `sudo` (falls back gracefully if `sudo` is unavailable or you are alrea
128
129
  mcmd --sudo "systemctl restart myservice"
129
130
  ```
130
131
 
132
+ `sudo -v` asks for the password first, on the terminal, when `mcmd` runs in its foreground. Each command then runs as
133
+ `sudo -n` wherever there is a terminal, so one that sudo would still ask a password for (`timestamp_timeout=0`, a
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`) `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)).
142
+
131
143
  Preview what a range expands to without running anything:
132
144
 
133
145
  ```bash
@@ -392,8 +404,10 @@ multiCMD.run_command(["systemctl", "restart", "nginx"])
392
404
  multiCMD.run_command(["id"], use_sudo=True)
393
405
  ```
394
406
 
395
- If `sudo` is not on `PATH`, or you are already root, the request is ignored with
396
- a warning instead of failing.
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).
397
411
 
398
412
  ## Timeout semantics
399
413
 
@@ -410,9 +424,11 @@ default, in the API and on the command line) disables it.
410
424
 
411
425
  Every command runs in a process group of its own, so a timeout, `stop()` or Ctrl-C reaches the
412
426
  whole process tree, not just the first process. On Python 3.11+ this uses `Popen(process_group=0)`;
413
- older Pythons start the command through a tiny exec wrapper. A command that reads the terminal (a
414
- password prompt, for example) fails at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for
415
- it, and `mcmd` also ignores them, which every command inherits through any shell.
427
+ older Pythons start the command through a tiny exec wrapper. A command that reads the terminal fails
428
+ at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for it, and `mcmd` also ignores them,
429
+ which every command inherits through any shell. A `sudo` of your own inside a command is the
430
+ exception: it stops, or under `mcmd` prints its prompt over and over, until a Ctrl-C. Use `--sudo` /
431
+ `use_sudo`, or run `sudo -v` first.
416
432
 
417
433
  Signals sent to your program's group do not reach the commands, so multiCMD stops them itself. One
418
434
  Ctrl-C (or a SIGTERM handler's `sys.exit()`) in a call waiting on the main thread, `join_threads()`
@@ -534,6 +550,44 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
534
550
  ```
535
551
 
536
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).
572
+
573
+ ## Upgrading to 1.71 from 1.70
574
+
575
+ - Nothing needs doing for a run in the foreground of a terminal whose sudo remembers the password between commands (the
576
+ default), for NOPASSWD rules, or with no terminal (cron, `ssh` without `-t`): those run as before.
577
+ - Fix: with `--sudo` / `use_sudo` on a terminal each command runs as `sudo -n`, so one that sudo would ask a password for
578
+ at that moment (`timestamp_timeout=0`, or the remembered password ran out mid-run) fails at once with
579
+ `sudo: a password is required`. 1.70 waited at sudo's prompt until a Ctrl-C (a password typed there showed on the
580
+ screen), or under `mcmd` printed the prompt over and over, or failed after a failed login that pam_faillock counted.
581
+ `Task.command` and `--dry-run` show the `-n`.
582
+ - Fix: `sudo -v` asks for the password only where multiCMD is in its terminal's foreground. In a background job
583
+ (`mcmd --sudo ... &`), under another `mcmd`, or under a script's `timeout` (without `--foreground`) it runs as `sudo -n -v` and asks nothing, so a run with nothing
584
+ remembered fails at once. 1.70 hung there (a program using the library as a background job stopped until `fg`), and a
585
+ password typed at the prompt went to the shell. Run `sudo -v` first, or run in the foreground.
586
+ - Changed: on a terminal, a sudo that signs in with no question (an ssh agent through pam_ssh_agent_auth, Kerberos) and
587
+ remembers nothing at that moment is refused where 1.70 ran the command: with `timestamp_timeout=0`, once the remembered
588
+ sign-in ran out mid-run, and in the background or under another `mcmd` when no `sudo -v` ran first. Give the commands
589
+ NOPASSWD. `Defaults noninteractive_auth` (sudo 1.9.10 and later) lets `sudo -n` sign in with no question, but then
590
+ pam_faillock counts each refusal of a password sudo as a failed login; sudo 1.9.9 (Ubuntu 22.04) does both by default.
537
591
 
538
592
  ## Upgrading to 1.70 from 1.69
539
593
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.70
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,7 +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
92
+ --sudo use sudo for commands ( sudo -v asks first; they run
93
+ as sudo -n on a terminal, or where sudo -v failed )
93
94
  -q, --quiet quiet mode: hide command output ( the summary still
94
95
  shows )
95
96
  -n, --dry-run print each command, quoted, instead of running it
@@ -153,6 +154,17 @@ Run with `sudo` (falls back gracefully if `sudo` is unavailable or you are alrea
153
154
  mcmd --sudo "systemctl restart myservice"
154
155
  ```
155
156
 
157
+ `sudo -v` asks for the password first, on the terminal, when `mcmd` runs in its foreground. Each command then runs as
158
+ `sudo -n` wherever there is a terminal, so one that sudo would still ask a password for (`timestamp_timeout=0`, a
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`) `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)).
167
+
156
168
  Preview what a range expands to without running anything:
157
169
 
158
170
  ```bash
@@ -417,8 +429,10 @@ multiCMD.run_command(["systemctl", "restart", "nginx"])
417
429
  multiCMD.run_command(["id"], use_sudo=True)
418
430
  ```
419
431
 
420
- If `sudo` is not on `PATH`, or you are already root, the request is ignored with
421
- a warning instead of failing.
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).
422
436
 
423
437
  ## Timeout semantics
424
438
 
@@ -435,9 +449,11 @@ default, in the API and on the command line) disables it.
435
449
 
436
450
  Every command runs in a process group of its own, so a timeout, `stop()` or Ctrl-C reaches the
437
451
  whole process tree, not just the first process. On Python 3.11+ this uses `Popen(process_group=0)`;
438
- older Pythons start the command through a tiny exec wrapper. A command that reads the terminal (a
439
- password prompt, for example) fails at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for
440
- it, and `mcmd` also ignores them, which every command inherits through any shell.
452
+ older Pythons start the command through a tiny exec wrapper. A command that reads the terminal fails
453
+ at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for it, and `mcmd` also ignores them,
454
+ which every command inherits through any shell. A `sudo` of your own inside a command is the
455
+ exception: it stops, or under `mcmd` prints its prompt over and over, until a Ctrl-C. Use `--sudo` /
456
+ `use_sudo`, or run `sudo -v` first.
441
457
 
442
458
  Signals sent to your program's group do not reach the commands, so multiCMD stops them itself. One
443
459
  Ctrl-C (or a SIGTERM handler's `sys.exit()`) in a call waiting on the main thread, `join_threads()`
@@ -559,6 +575,44 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
559
575
  ```
560
576
 
561
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).
597
+
598
+ ## Upgrading to 1.71 from 1.70
599
+
600
+ - Nothing needs doing for a run in the foreground of a terminal whose sudo remembers the password between commands (the
601
+ default), for NOPASSWD rules, or with no terminal (cron, `ssh` without `-t`): those run as before.
602
+ - Fix: with `--sudo` / `use_sudo` on a terminal each command runs as `sudo -n`, so one that sudo would ask a password for
603
+ at that moment (`timestamp_timeout=0`, or the remembered password ran out mid-run) fails at once with
604
+ `sudo: a password is required`. 1.70 waited at sudo's prompt until a Ctrl-C (a password typed there showed on the
605
+ screen), or under `mcmd` printed the prompt over and over, or failed after a failed login that pam_faillock counted.
606
+ `Task.command` and `--dry-run` show the `-n`.
607
+ - Fix: `sudo -v` asks for the password only where multiCMD is in its terminal's foreground. In a background job
608
+ (`mcmd --sudo ... &`), under another `mcmd`, or under a script's `timeout` (without `--foreground`) it runs as `sudo -n -v` and asks nothing, so a run with nothing
609
+ remembered fails at once. 1.70 hung there (a program using the library as a background job stopped until `fg`), and a
610
+ password typed at the prompt went to the shell. Run `sudo -v` first, or run in the foreground.
611
+ - Changed: on a terminal, a sudo that signs in with no question (an ssh agent through pam_ssh_agent_auth, Kerberos) and
612
+ remembers nothing at that moment is refused where 1.70 ran the command: with `timestamp_timeout=0`, once the remembered
613
+ sign-in ran out mid-run, and in the background or under another `mcmd` when no `sudo -v` ran first. Give the commands
614
+ NOPASSWD. `Defaults noninteractive_auth` (sudo 1.9.10 and later) lets `sudo -n` sign in with no question, but then
615
+ pam_faillock counts each refusal of a password sudo as a failed login; sudo 1.9.9 (Ubuntu 22.04) does both by default.
562
616
 
563
617
  ## Upgrading to 1.70 from 1.69
564
618
 
@@ -29,9 +29,9 @@ import traceback
29
29
  from pprint import pformat
30
30
 
31
31
  #%% global vars
32
- version = '1.70'
32
+ version = '1.72'
33
33
  __version__ = version
34
- COMMIT_DATE = '2026-11-23'
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()
@@ -59,7 +59,7 @@ _HAS_PROCESS_GROUP = sys.version_info >= (3, 11)
59
59
  # duplicated, writing a caller's open file twice. On 3.7 - 3.10 preexec_fn runs the at-fork hooks, Python code in the
60
60
  # parent: a Ctrl-C at the start of logging's _releaseLock can leave its lock held, and every later command started on
61
61
  # another thread hangs on it.
62
- # Not a new session ( setsid ) either: that would hide the terminal from sudo.
62
+ # Not a new session ( setsid ) either: that would hide the terminal from sudo, and with it what sudo -v remembered for it.
63
63
  # It runs in this process's own environment ( so it starts wherever this Python does, LD_LIBRARY_PATH and the
64
64
  # like included ). It runs the command only once the caller has it registered: its second argument is the read end of a
65
65
  # pipe ( passed to it alone ) on which the caller writes one byte then ( see _popen ). A caller interrupted inside Popen
@@ -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
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,11 +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
- formatedCommands = [[SUDO_PATH] + command for command in formatedCommands]
2526
2528
  env = _check_env(env, 'env', drop_empty=True)
2527
2529
  extra_env = _check_env(extra_env, 'extra_env', allow_none=True)
2528
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]
2529
2534
  # one snapshot shared by every task of the call
2530
2535
  tasks = [Task(command) for command in formatedCommands]
2531
2536
  # a call the main thread makes once the exit hook has begun ( from an atexit handler: see _cut_by_exit )
@@ -2538,18 +2543,63 @@ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, ext
2538
2543
  task._pass_fds = pass_fds
2539
2544
  task._at_exit = at_exit
2540
2545
  task._unread = unread
2541
- return tasks, bool(use_sudo)
2546
+ return tasks
2547
+
2548
+ def _terminal():
2549
+ '''
2550
+ Where this process stands with its controlling terminal ( internal ): None with none ( /dev/tty does not open: cron,
2551
+ ssh without -t, a session of its own; and off POSIX ), True in its foreground process group, False in a background
2552
+ one ( a job started with &, a program run by another multiCMD ), or when the terminal cannot say ( False: sudo could
2553
+ still stop on it )
2554
+ '''
2555
+ if not _IS_POSIX:
2556
+ return None
2557
+ try:
2558
+ fd = os.open('/dev/tty', os.O_RDWR | os.O_NOCTTY)
2559
+ except OSError:
2560
+ return None
2561
+ try:
2562
+ return os.tcgetpgrp(fd) == os.getpgrp()
2563
+ except OSError:
2564
+ return False
2565
+ finally:
2566
+ os.close(fd)
2542
2567
 
2543
- def _validate_sudo():
2568
+ def _sudo(dry_run):
2544
2569
  '''
2545
- Validate sudo access before running sudo commands ( internal )
2546
- It runs in the foreground on the terminal, so sudo can ask for a password and cache the
2547
- per-terminal ticket that the commands ( in process groups of their own, same session ) then use.
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):
2587
+ '''
2588
+ Run sudo -v before sudo commands, `where` being _terminal()'s answer; whether it signed in ( exits 0 ) ( internal )
2589
+ In the terminal's foreground sudo can ask for a password, and what it then remembers for the terminal is what the
2590
+ commands ( sudo -n, in process groups of their own, same session ) run on. In a background process group it could only
2591
+ stop ( or loop, with SIGTTIN ignored ), so there it runs as sudo -n -v, which asks nothing, and its refusal ( stderr )
2592
+ goes nowhere: written to the terminal from a background group under `stty tostop` it stops the whole group ( SIGTTOU )
2593
+ until someone brings it to the foreground, and this call waits. Each command reports its own refusal on its own pipes.
2594
+ With no terminal it runs as it always has ( it fails, asks an askpass helper, or signs in with no question ).
2548
2595
  '''
2549
2596
  try:
2550
- 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
2551
2600
  except OSError as e:
2552
2601
  _write_error(f'sudo validation failed: {e}')
2602
+ return False
2553
2603
 
2554
2604
  def __format_command(command,expand = False,shell = False,variables = None):
2555
2605
  '''
@@ -2737,7 +2787,9 @@ def run_command(command, timeout=0,max_threads=1,quiet=False,dry_run=False,with_
2737
2787
  return_object: Whether to return the Task object
2738
2788
  wait_for_return: Whether to wait for the return of the command
2739
2789
  sem: The semaphore to use for threading
2740
- use_sudo: Whether to use sudo for commands
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
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 )
2741
2793
  raise_error: Whether to raise an error if the command fails
2742
2794
  prefix: Whether to prefix output lines with [#] when commands run at once ( never for one command )
2743
2795
  color: Whether to color output lines ( None: when commands run at once on a terminal without NO_COLOR )
@@ -2793,7 +2845,9 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2793
2845
  parse: Whether to parse ranged input
2794
2846
  wait_for_return: Whether to wait for the return of the commands
2795
2847
  sem: The semaphore to use for threading
2796
- use_sudo: Whether to use sudo for commands
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
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 )
2797
2851
  raise_error: Whether to raise an error if the command fails
2798
2852
  prefix: Whether to prefix output lines with [#], the command's 1-based position, when commands run at once
2799
2853
  color: Whether to color output lines per command ( None: when commands run at once on a terminal without NO_COLOR )
@@ -2817,9 +2871,12 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2817
2871
  list: The output of the commands ( list[None] | list[int] | list[list[str]] | list[Task] | None )
2818
2872
  '''
2819
2873
  # initialize the tasks
2820
- 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)
2821
2878
  # run the tasks with max_threads. if max_threads is 0, use the number of commands
2822
- if max_threads < 1:
2879
+ if unlimited:
2823
2880
  max_threads = len(tasks)
2824
2881
  # concurrent runs get [#] prefixes ( when asked ) and colors ( on a terminal )
2825
2882
  concurrent = len(tasks) > 1 and max_threads != 1
@@ -2829,8 +2886,6 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2829
2886
  use_pty = _resolve_pty(pty)
2830
2887
  if not sem:
2831
2888
  sem = threading.Semaphore(max_threads) # Limit concurrent sessions
2832
- if use_sudo and not dry_run:
2833
- _validate_sudo()
2834
2889
  if dry_run:
2835
2890
  # nothing runs: show each command once, quoted so it can be pasted into a shell
2836
2891
  for task in tasks:
@@ -3187,7 +3242,7 @@ def _run_cli():
3187
3242
  parser.add_argument('-p','--parse', action='store_true',help='Parse ranged input and expand them into multiple commands')
3188
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 )')
3189
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 )')
3190
- parser.add_argument('--sudo', action='store_true',help='use sudo for commands')
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 )')
3191
3246
  parser.add_argument('-q','--quiet', action='store_true',help='quiet mode: hide command output ( the summary still shows )')
3192
3247
  parser.add_argument('-n','--dry-run', action='store_true',help='print each command, quoted, instead of running it')
3193
3248
  parser.add_argument('--shell', action='store_true',help='run each command through /bin/sh -c ( pipes, ;, > and globs work )')
@@ -16,11 +16,18 @@ def test_quiet_dry_run_prints_nothing(capsys):
16
16
 
17
17
  def test_dry_run_skips_sudo_validation(monkeypatch, capsys):
18
18
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
19
- def fail():
19
+ # ( no terminal: with one the prefix is sudo -n, see test_sudo.py )
20
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: None)
21
+ def fail(where):
20
22
  raise AssertionError('sudo -v must not run in a dry run')
21
23
  monkeypatch.setattr(multiCMD, '_validate_sudo', fail)
24
+ # ( with no terminal it shows what runs where sudo -v signs in )
22
25
  run_commands([['id']], dry_run=True, use_sudo=True)
23
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) == []
24
31
 
25
32
 
26
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'],
@@ -34,8 +34,10 @@ def test_shell_mode_quotes_list_commands():
34
34
 
35
35
  def test_shell_mode_with_sudo_wraps_the_shell(monkeypatch):
36
36
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
37
- tasks, used = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
38
- assert used is True
37
+ # ( no terminal: with one the prefix is sudo -n, see test_sudo.py )
38
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: None)
39
+ monkeypatch.setattr(multiCMD, '_validate_sudo', lambda where: True)
40
+ tasks = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
39
41
  assert tasks[0].command == ['/usr/bin/sudo', '/bin/sh', '-c', 'echo hi']
40
42
 
41
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
@@ -0,0 +1,338 @@
1
+ import os
2
+ import select
3
+ import subprocess
4
+ import sys
5
+
6
+ import pytest
7
+
8
+ import multiCMD
9
+ from conftest import PACKAGE_ROOT, has_sudo_binary
10
+ from multiCMD import run_command, set_sudo
11
+
12
+
13
+ def test_set_sudo_false():
14
+ multiCMD.USE_SUDO = True
15
+ set_sudo(False)
16
+ assert multiCMD.USE_SUDO is False
17
+
18
+
19
+ def test_set_sudo_true_when_root():
20
+ if os.geteuid() != 0:
21
+ pytest.skip("requires root to exercise root-disables-sudo path")
22
+ set_sudo(True)
23
+ assert multiCMD.USE_SUDO is False
24
+
25
+
26
+ def test_set_sudo_true_without_sudo_binary(capsys):
27
+ multiCMD.SUDO_PATH = None
28
+ if os.geteuid() == 0:
29
+ pytest.skip("root path short-circuits before SUDO_PATH check")
30
+ set_sudo(True)
31
+ assert multiCMD.USE_SUDO is False
32
+ err = capsys.readouterr().err
33
+ assert "sudo not found" in err
34
+
35
+
36
+ @pytest.mark.sudo
37
+ def test_set_sudo_true_non_root_with_binary():
38
+ if os.geteuid() == 0 or not has_sudo_binary():
39
+ pytest.skip("needs non-root and sudo in PATH")
40
+ set_sudo(True)
41
+ assert multiCMD.USE_SUDO is True
42
+
43
+
44
+ def test_use_sudo_none_path_does_not_crash():
45
+ multiCMD.SUDO_PATH = None
46
+ # Must not raise TypeError from Popen([None, ...])
47
+ result = run_command(["echo", "ok"], quiet=True, use_sudo=True)
48
+ assert result == ["ok"]
49
+
50
+
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. 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 = []
61
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
62
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: where)
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)
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]
68
+ # shell mode wraps the shell, and set_sudo's global takes the same prefix
69
+ tasks = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
70
+ assert tasks[0].command == prefix + ['/bin/sh', '-c', 'echo hi']
71
+ multiCMD.USE_SUDO = True
72
+ tasks = multiCMD._build_tasks(['id'])
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 == []
125
+
126
+
127
+ def test_no_sudo_asks_nothing_of_the_terminal(monkeypatch):
128
+ def fail():
129
+ raise AssertionError('the terminal is looked at only for sudo')
130
+ monkeypatch.setattr(multiCMD, '_terminal', fail)
131
+ tasks = multiCMD._build_tasks(['id'])
132
+ assert tasks[0].command == ['id']
133
+
134
+
135
+ # the background one writes its refusal nowhere ( stderr to /dev/null ): to the terminal, under `stty tostop`, it stops the
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
138
+ @pytest.mark.parametrize('where, argv, kwargs', [(None, ['/usr/bin/sudo', '-v'], {}), (True, ['/usr/bin/sudo', '-v'], {}),
139
+ (False, ['/usr/bin/sudo', '-n', '-v'], {'stderr': subprocess.DEVNULL})])
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):
142
+ calls = []
143
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/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
149
+ assert calls == [((argv,), kwargs)]
150
+
151
+
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):
185
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
186
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: where)
187
+ multiCMD.run_commands([['id']], dry_run=True, use_sudo=True)
188
+ assert capsys.readouterr().out == '/usr/bin/sudo -n id\n'
189
+
190
+
191
+ class _FakeTty:
192
+ '''os.open( '/dev/tty' ) and os.tcgetpgrp() for _terminal(): the descriptor is a real one ( /dev/null ), and closes are counted'''
193
+ def __init__(self, monkeypatch, opens=True, pgrp=None, error=False):
194
+ self.fds, self.closed = [], []
195
+ real_open, real_close = os.open, os.close
196
+ def fake_open(path, flags, *args):
197
+ assert path == '/dev/tty' and flags & os.O_NOCTTY
198
+ if not opens:
199
+ raise OSError(6, 'No such device or address', path)
200
+ fd = real_open(os.devnull, os.O_RDONLY)
201
+ self.fds.append(fd)
202
+ return fd
203
+ def fake_close(fd):
204
+ self.closed.append(fd)
205
+ real_close(fd)
206
+ def fake_tcgetpgrp(fd):
207
+ assert fd in self.fds
208
+ if error:
209
+ raise OSError(25, 'Inappropriate ioctl for device')
210
+ return os.getpgrp() if pgrp is None else pgrp
211
+ monkeypatch.setattr(multiCMD.os, 'open', fake_open)
212
+ monkeypatch.setattr(multiCMD.os, 'close', fake_close)
213
+ monkeypatch.setattr(multiCMD.os, 'tcgetpgrp', fake_tcgetpgrp)
214
+
215
+
216
+ @pytest.mark.skipif(os.name != 'posix', reason='a controlling terminal is POSIX only')
217
+ @pytest.mark.parametrize('opens, pgrp, error, answer', [
218
+ (False, None, False, None),
219
+ (True, None, False, True),
220
+ (True, -1, False, False),
221
+ (True, None, True, False),
222
+ ])
223
+ def test_terminal_answers(monkeypatch, opens, pgrp, error, answer):
224
+ tty = _FakeTty(monkeypatch, opens=opens, pgrp=os.getpgrp() + 1 if pgrp == -1 else pgrp, error=error)
225
+ assert multiCMD._terminal() is answer
226
+ # the descriptor it opened is closed, whatever the answer
227
+ assert tty.closed == tty.fds
228
+
229
+
230
+ def test_terminal_is_none_off_posix(monkeypatch):
231
+ monkeypatch.setattr(multiCMD, '_IS_POSIX', False)
232
+ monkeypatch.setattr(multiCMD.os, 'open', lambda *args: pytest.fail('/dev/tty is not opened off POSIX'))
233
+ assert multiCMD._terminal() is None
234
+
235
+
236
+ # a session leader that takes the pty as its controlling terminal ( TIOCSCTTY ) is in its foreground, and so is a child
237
+ # left in its process group; a child moved to a process group of its own is not; and with no controlling terminal there
238
+ # is none
239
+ _TERMINAL_PROBE = r'''
240
+ import fcntl, os, sys, termios
241
+ sys.path.insert(0, sys.argv[1])
242
+ import multiCMD
243
+ if sys.argv[2] == 'tty':
244
+ fcntl.ioctl(0, termios.TIOCSCTTY, 0)
245
+ print('leader', multiCMD._terminal(), flush=True)
246
+ for name in ('same group', 'own group'):
247
+ pid = os.fork()
248
+ if pid == 0:
249
+ if name == 'own group':
250
+ os.setpgid(0, 0)
251
+ print(name, multiCMD._terminal(), flush=True)
252
+ os._exit(0)
253
+ os.waitpid(pid, 0)
254
+ '''
255
+
256
+
257
+ @pytest.mark.skipif(os.name != 'posix', reason='a controlling terminal is POSIX only')
258
+ @pytest.mark.parametrize('kind, expected', [('tty', 'leader True\nsame group True\nown group False\n'),
259
+ ('none', 'leader None\nsame group None\nown group None\n')])
260
+ def test_terminal_on_a_real_pty(kind, expected):
261
+ import pty
262
+ master, slave = pty.openpty()
263
+ try:
264
+ proc = subprocess.run([sys.executable, '-c', _TERMINAL_PROBE, str(PACKAGE_ROOT), kind], stdin=slave if kind == 'tty' else subprocess.DEVNULL,
265
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, universal_newlines=True, timeout=60)
266
+ finally:
267
+ os.close(master)
268
+ os.close(slave)
269
+ assert proc.stderr == ''
270
+ assert proc.stdout == expected
271
+
272
+
273
+ # a program using the library, with `stty tostop` on its terminal and nothing remembered by sudo: sudo's refusal, written to the
274
+ # terminal from a background process group, stopped the group ( SIGTTOU ) and the call waited. The stand-in sudo refuses
275
+ # as sudo does, on stderr. The probe is the terminal's session leader ( in its foreground ); the background run forks a child
276
+ # into a process group of its own, which makes the call and exits 0 when the refusal came back as the command's own
277
+ # stderr. LIMIT: the call takes milliseconds, so a regression waits the whole of it, 10 s, and the stopped group is killed
278
+ _TOSTOP_PROBE = r'''
279
+ import fcntl, os, signal, sys, termios, time
280
+ sys.path.insert(0, sys.argv[1])
281
+ import multiCMD
282
+ multiCMD.SUDO_PATH = sys.argv[3]
283
+ LIMIT = 10
284
+ fcntl.ioctl(0, termios.TIOCSCTTY, 0)
285
+
286
+ def call():
287
+ task = multiCMD.run_command(['id'], quiet=True, use_sudo=True, return_object=True)
288
+ return 0 if (task.returncode, task.stderr) == (1, ['sudo: a password is required']) else 3
289
+
290
+ if sys.argv[2] == 'foreground':
291
+ print('foreground', call(), flush=True)
292
+ sys.exit(0)
293
+ pid = os.fork()
294
+ if pid == 0:
295
+ os.setpgid(0, 0)
296
+ os._exit(call())
297
+ deadline = time.monotonic() + LIMIT
298
+ while time.monotonic() < deadline:
299
+ done, status = os.waitpid(pid, os.WNOHANG)
300
+ if done:
301
+ print('background', os.WEXITSTATUS(status) if os.WIFEXITED(status) else 'signal %d' % os.WTERMSIG(status), flush=True)
302
+ sys.exit(0)
303
+ time.sleep(0.02)
304
+ os.killpg(pid, signal.SIGKILL)
305
+ os.waitpid(pid, 0)
306
+ print('background hung', flush=True)
307
+ '''
308
+
309
+
310
+ @pytest.mark.skipif(os.name != 'posix', reason='a controlling terminal is POSIX only')
311
+ @pytest.mark.parametrize('where', ['foreground', 'background'])
312
+ def test_sudo_validation_does_not_stop_on_a_tostop_terminal(tmp_path, where):
313
+ import pty
314
+ import termios
315
+ sudo = tmp_path / 'sudo'
316
+ sudo.write_text('#!/bin/sh\necho "sudo: a password is required" >&2\nexit 1\n')
317
+ sudo.chmod(0o755)
318
+ master, slave = pty.openpty()
319
+ try:
320
+ attrs = termios.tcgetattr(slave)
321
+ attrs[3] |= termios.TOSTOP
322
+ termios.tcsetattr(slave, termios.TCSANOW, attrs)
323
+ proc = subprocess.run([sys.executable, '-c', _TOSTOP_PROBE, str(PACKAGE_ROOT), where, str(sudo)], stdin=slave,
324
+ stdout=subprocess.PIPE, stderr=slave, start_new_session=True, universal_newlines=True, timeout=60)
325
+ # what the probe wrote to its terminal ( a traceback, sudo's refusal ), for a failure's message
326
+ shown = b''
327
+ while select.select([master], [], [], 0)[0]:
328
+ try:
329
+ data = os.read(master, 4096)
330
+ except OSError:
331
+ break
332
+ if not data:
333
+ break
334
+ shown += data
335
+ finally:
336
+ os.close(master)
337
+ os.close(slave)
338
+ assert proc.stdout == where + ' 0\n', shown
@@ -141,8 +141,9 @@ def test_command_that_is_not_executable_is_126(launcher, tmp_path):
141
141
  def test_sudo_validation_runs_in_the_foreground(monkeypatch):
142
142
  calls = []
143
143
  monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
144
- monkeypatch.setattr(subprocess, 'run', lambda *args, **kwargs: calls.append((args, kwargs)))
145
- multiCMD._validate_sudo()
144
+ # ( in the terminal's foreground: elsewhere see test_sudo.py )
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
146
147
  assert calls == [((['/usr/bin/sudo', '-v'],), {})]
147
148
 
148
149
 
@@ -1,45 +0,0 @@
1
- import os
2
-
3
- import pytest
4
-
5
- import multiCMD
6
- from conftest import has_sudo_binary
7
- from multiCMD import run_command, set_sudo
8
-
9
-
10
- def test_set_sudo_false():
11
- multiCMD.USE_SUDO = True
12
- set_sudo(False)
13
- assert multiCMD.USE_SUDO is False
14
-
15
-
16
- def test_set_sudo_true_when_root():
17
- if os.geteuid() != 0:
18
- pytest.skip("requires root to exercise root-disables-sudo path")
19
- set_sudo(True)
20
- assert multiCMD.USE_SUDO is False
21
-
22
-
23
- def test_set_sudo_true_without_sudo_binary(capsys):
24
- multiCMD.SUDO_PATH = None
25
- if os.geteuid() == 0:
26
- pytest.skip("root path short-circuits before SUDO_PATH check")
27
- set_sudo(True)
28
- assert multiCMD.USE_SUDO is False
29
- err = capsys.readouterr().err
30
- assert "sudo not found" in err
31
-
32
-
33
- @pytest.mark.sudo
34
- def test_set_sudo_true_non_root_with_binary():
35
- if os.geteuid() == 0 or not has_sudo_binary():
36
- pytest.skip("needs non-root and sudo in PATH")
37
- set_sudo(True)
38
- assert multiCMD.USE_SUDO is True
39
-
40
-
41
- def test_use_sudo_none_path_does_not_crash():
42
- multiCMD.SUDO_PATH = None
43
- # Must not raise TypeError from Popen([None, ...])
44
- result = run_command(["echo", "ok"], quiet=True, use_sudo=True)
45
- assert result == ["ok"]
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