multiCMD 1.70__tar.gz → 1.71__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.71}/PKG-INFO +34 -6
  2. {multicmd-1.70 → multicmd-1.71}/README.md +33 -5
  3. {multicmd-1.70 → multicmd-1.71}/multiCMD.egg-info/PKG-INFO +34 -6
  4. {multicmd-1.70 → multicmd-1.71}/multiCMD.py +45 -11
  5. {multicmd-1.70 → multicmd-1.71}/tests/test_api.py +2 -0
  6. {multicmd-1.70 → multicmd-1.71}/tests/test_parsing.py +2 -0
  7. multicmd-1.71/tests/test_sudo.py +245 -0
  8. {multicmd-1.70 → multicmd-1.71}/tests/test_supervision.py +2 -0
  9. multicmd-1.70/tests/test_sudo.py +0 -45
  10. {multicmd-1.70 → multicmd-1.71}/LICENSE +0 -0
  11. {multicmd-1.70 → multicmd-1.71}/multiCMD.egg-info/SOURCES.txt +0 -0
  12. {multicmd-1.70 → multicmd-1.71}/multiCMD.egg-info/dependency_links.txt +0 -0
  13. {multicmd-1.70 → multicmd-1.71}/multiCMD.egg-info/entry_points.txt +0 -0
  14. {multicmd-1.70 → multicmd-1.71}/multiCMD.egg-info/top_level.txt +0 -0
  15. {multicmd-1.70 → multicmd-1.71}/scripts/multiCMD +0 -0
  16. {multicmd-1.70 → multicmd-1.71}/setup.cfg +0 -0
  17. {multicmd-1.70 → multicmd-1.71}/setup.py +0 -0
  18. {multicmd-1.70 → multicmd-1.71}/tests/test_async_executor.py +0 -0
  19. {multicmd-1.70 → multicmd-1.71}/tests/test_cli.py +0 -0
  20. {multicmd-1.70 → multicmd-1.71}/tests/test_cli_closed_stdout.py +0 -0
  21. {multicmd-1.70 → multicmd-1.71}/tests/test_cli_failed_stdout.py +0 -0
  22. {multicmd-1.70 → multicmd-1.71}/tests/test_cli_input.py +0 -0
  23. {multicmd-1.70 → multicmd-1.71}/tests/test_cli_summary.py +0 -0
  24. {multicmd-1.70 → multicmd-1.71}/tests/test_display.py +0 -0
  25. {multicmd-1.70 → multicmd-1.71}/tests/test_embed.py +0 -0
  26. {multicmd-1.70 → multicmd-1.71}/tests/test_env.py +0 -0
  27. {multicmd-1.70 → multicmd-1.71}/tests/test_expand_ranges.py +0 -0
  28. {multicmd-1.70 → multicmd-1.71}/tests/test_handover.py +0 -0
  29. {multicmd-1.70 → multicmd-1.71}/tests/test_helpers.py +0 -0
  30. {multicmd-1.70 → multicmd-1.71}/tests/test_interrupts.py +0 -0
  31. {multicmd-1.70 → multicmd-1.71}/tests/test_packaging.py +0 -0
  32. {multicmd-1.70 → multicmd-1.71}/tests/test_pass_fds.py +0 -0
  33. {multicmd-1.70 → multicmd-1.71}/tests/test_ping.py +0 -0
  34. {multicmd-1.70 → multicmd-1.71}/tests/test_pool.py +0 -0
  35. {multicmd-1.70 → multicmd-1.71}/tests/test_process_groups.py +0 -0
  36. {multicmd-1.70 → multicmd-1.71}/tests/test_pty.py +0 -0
  37. {multicmd-1.70 → multicmd-1.71}/tests/test_reader.py +0 -0
  38. {multicmd-1.70 → multicmd-1.71}/tests/test_reader_quit.py +0 -0
  39. {multicmd-1.70 → multicmd-1.71}/tests/test_regressions.py +0 -0
  40. {multicmd-1.70 → multicmd-1.71}/tests/test_run_command.py +0 -0
  41. {multicmd-1.70 → multicmd-1.71}/tests/test_run_commands.py +0 -0
  42. {multicmd-1.70 → multicmd-1.71}/tests/test_task.py +0 -0
  43. {multicmd-1.70 → multicmd-1.71}/tests/test_terminal_width.py +0 -0
  44. {multicmd-1.70 → multicmd-1.71}/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.71
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; on a
93
+ terminal they run as sudo -n )
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,11 @@ 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`) it runs as plain `sudo`.
161
+
156
162
  Preview what a range expands to without running anything:
157
163
 
158
164
  ```bash
@@ -418,7 +424,8 @@ multiCMD.run_command(["id"], use_sudo=True)
418
424
  ```
419
425
 
420
426
  If `sudo` is not on `PATH`, or you are already root, the request is ignored with
421
- a warning instead of failing.
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).
422
429
 
423
430
  ## Timeout semantics
424
431
 
@@ -435,9 +442,11 @@ default, in the API and on the command line) disables it.
435
442
 
436
443
  Every command runs in a process group of its own, so a timeout, `stop()` or Ctrl-C reaches the
437
444
  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.
445
+ older Pythons start the command through a tiny exec wrapper. A command that reads the terminal fails
446
+ at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for it, and `mcmd` also ignores them,
447
+ which every command inherits through any shell. A `sudo` of your own inside a command is the
448
+ exception: it stops, or under `mcmd` prints its prompt over and over, until a Ctrl-C. Use `--sudo` /
449
+ `use_sudo`, or run `sudo -v` first.
441
450
 
442
451
  Signals sent to your program's group do not reach the commands, so multiCMD stops them itself. One
443
452
  Ctrl-C (or a SIGTERM handler's `sys.exit()`) in a call waiting on the main thread, `join_threads()`
@@ -560,6 +569,25 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
560
569
 
561
570
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
562
571
 
572
+ ## Upgrading to 1.71 from 1.70
573
+
574
+ - Nothing needs doing for a run in the foreground of a terminal whose sudo remembers the password between commands (the
575
+ default), for NOPASSWD rules, or with no terminal (cron, `ssh` without `-t`): those run as before.
576
+ - Fix: with `--sudo` / `use_sudo` on a terminal each command runs as `sudo -n`, so one that sudo would ask a password for
577
+ at that moment (`timestamp_timeout=0`, or the remembered password ran out mid-run) fails at once with
578
+ `sudo: a password is required`. 1.70 waited at sudo's prompt until a Ctrl-C (a password typed there showed on the
579
+ screen), or under `mcmd` printed the prompt over and over, or failed after a failed login that pam_faillock counted.
580
+ `Task.command` and `--dry-run` show the `-n`.
581
+ - Fix: `sudo -v` asks for the password only where multiCMD is in its terminal's foreground. In a background job
582
+ (`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
583
+ remembered fails at once. 1.70 hung there (a program using the library as a background job stopped until `fg`), and a
584
+ password typed at the prompt went to the shell. Run `sudo -v` first, or run in the foreground.
585
+ - Changed: on a terminal, a sudo that signs in with no question (an ssh agent through pam_ssh_agent_auth, Kerberos) and
586
+ remembers nothing at that moment is refused where 1.70 ran the command: with `timestamp_timeout=0`, once the remembered
587
+ sign-in ran out mid-run, and in the background or under another `mcmd` when no `sudo -v` ran first. Give the commands
588
+ NOPASSWD. `Defaults noninteractive_auth` (sudo 1.9.10 and later) lets `sudo -n` sign in with no question, but then
589
+ pam_faillock counts each refusal of a password sudo as a failed login; sudo 1.9.9 (Ubuntu 22.04) does both by default.
590
+
563
591
  ## Upgrading to 1.70 from 1.69
564
592
 
565
593
  - Nothing needs doing. `mcmd` is unchanged.
@@ -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; on a
68
+ terminal they run as sudo -n )
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,11 @@ 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`) it runs as plain `sudo`.
136
+
131
137
  Preview what a range expands to without running anything:
132
138
 
133
139
  ```bash
@@ -393,7 +399,8 @@ multiCMD.run_command(["id"], use_sudo=True)
393
399
  ```
394
400
 
395
401
  If `sudo` is not on `PATH`, or you are already root, the request is ignored with
396
- a warning instead of failing.
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).
397
404
 
398
405
  ## Timeout semantics
399
406
 
@@ -410,9 +417,11 @@ default, in the API and on the command line) disables it.
410
417
 
411
418
  Every command runs in a process group of its own, so a timeout, `stop()` or Ctrl-C reaches the
412
419
  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.
420
+ older Pythons start the command through a tiny exec wrapper. A command that reads the terminal fails
421
+ at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for it, and `mcmd` also ignores them,
422
+ which every command inherits through any shell. A `sudo` of your own inside a command is the
423
+ exception: it stops, or under `mcmd` prints its prompt over and over, until a Ctrl-C. Use `--sudo` /
424
+ `use_sudo`, or run `sudo -v` first.
416
425
 
417
426
  Signals sent to your program's group do not reach the commands, so multiCMD stops them itself. One
418
427
  Ctrl-C (or a SIGTERM handler's `sys.exit()`) in a call waiting on the main thread, `join_threads()`
@@ -535,6 +544,25 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
535
544
 
536
545
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
537
546
 
547
+ ## Upgrading to 1.71 from 1.70
548
+
549
+ - Nothing needs doing for a run in the foreground of a terminal whose sudo remembers the password between commands (the
550
+ default), for NOPASSWD rules, or with no terminal (cron, `ssh` without `-t`): those run as before.
551
+ - Fix: with `--sudo` / `use_sudo` on a terminal each command runs as `sudo -n`, so one that sudo would ask a password for
552
+ at that moment (`timestamp_timeout=0`, or the remembered password ran out mid-run) fails at once with
553
+ `sudo: a password is required`. 1.70 waited at sudo's prompt until a Ctrl-C (a password typed there showed on the
554
+ screen), or under `mcmd` printed the prompt over and over, or failed after a failed login that pam_faillock counted.
555
+ `Task.command` and `--dry-run` show the `-n`.
556
+ - Fix: `sudo -v` asks for the password only where multiCMD is in its terminal's foreground. In a background job
557
+ (`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
558
+ remembered fails at once. 1.70 hung there (a program using the library as a background job stopped until `fg`), and a
559
+ password typed at the prompt went to the shell. Run `sudo -v` first, or run in the foreground.
560
+ - Changed: on a terminal, a sudo that signs in with no question (an ssh agent through pam_ssh_agent_auth, Kerberos) and
561
+ remembers nothing at that moment is refused where 1.70 ran the command: with `timestamp_timeout=0`, once the remembered
562
+ sign-in ran out mid-run, and in the background or under another `mcmd` when no `sudo -v` ran first. Give the commands
563
+ NOPASSWD. `Defaults noninteractive_auth` (sudo 1.9.10 and later) lets `sudo -n` sign in with no question, but then
564
+ pam_faillock counts each refusal of a password sudo as a failed login; sudo 1.9.9 (Ubuntu 22.04) does both by default.
565
+
538
566
  ## Upgrading to 1.70 from 1.69
539
567
 
540
568
  - Nothing needs doing. `mcmd` is unchanged.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: multiCMD
3
- Version: 1.70
3
+ Version: 1.71
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; on a
93
+ terminal they run as sudo -n )
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,11 @@ 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`) it runs as plain `sudo`.
161
+
156
162
  Preview what a range expands to without running anything:
157
163
 
158
164
  ```bash
@@ -418,7 +424,8 @@ multiCMD.run_command(["id"], use_sudo=True)
418
424
  ```
419
425
 
420
426
  If `sudo` is not on `PATH`, or you are already root, the request is ignored with
421
- a warning instead of failing.
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).
422
429
 
423
430
  ## Timeout semantics
424
431
 
@@ -435,9 +442,11 @@ default, in the API and on the command line) disables it.
435
442
 
436
443
  Every command runs in a process group of its own, so a timeout, `stop()` or Ctrl-C reaches the
437
444
  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.
445
+ older Pythons start the command through a tiny exec wrapper. A command that reads the terminal fails
446
+ at once instead of hanging: multiCMD blocks SIGTTIN/SIGTTOU for it, and `mcmd` also ignores them,
447
+ which every command inherits through any shell. A `sudo` of your own inside a command is the
448
+ exception: it stops, or under `mcmd` prints its prompt over and over, until a Ctrl-C. Use `--sudo` /
449
+ `use_sudo`, or run `sudo -v` first.
441
450
 
442
451
  Signals sent to your program's group do not reach the commands, so multiCMD stops them itself. One
443
452
  Ctrl-C (or a SIGTERM handler's `sys.exit()`) in a call waiting on the main thread, `join_threads()`
@@ -560,6 +569,25 @@ pytest -m "not slow" # skip intentional sleep-heavy cases
560
569
 
561
570
  `test_expand_ranges_perf.py` is a manual performance microbenchmark and is not collected by pytest.
562
571
 
572
+ ## Upgrading to 1.71 from 1.70
573
+
574
+ - Nothing needs doing for a run in the foreground of a terminal whose sudo remembers the password between commands (the
575
+ default), for NOPASSWD rules, or with no terminal (cron, `ssh` without `-t`): those run as before.
576
+ - Fix: with `--sudo` / `use_sudo` on a terminal each command runs as `sudo -n`, so one that sudo would ask a password for
577
+ at that moment (`timestamp_timeout=0`, or the remembered password ran out mid-run) fails at once with
578
+ `sudo: a password is required`. 1.70 waited at sudo's prompt until a Ctrl-C (a password typed there showed on the
579
+ screen), or under `mcmd` printed the prompt over and over, or failed after a failed login that pam_faillock counted.
580
+ `Task.command` and `--dry-run` show the `-n`.
581
+ - Fix: `sudo -v` asks for the password only where multiCMD is in its terminal's foreground. In a background job
582
+ (`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
583
+ remembered fails at once. 1.70 hung there (a program using the library as a background job stopped until `fg`), and a
584
+ password typed at the prompt went to the shell. Run `sudo -v` first, or run in the foreground.
585
+ - Changed: on a terminal, a sudo that signs in with no question (an ssh agent through pam_ssh_agent_auth, Kerberos) and
586
+ remembers nothing at that moment is refused where 1.70 ran the command: with `timestamp_timeout=0`, once the remembered
587
+ sign-in ran out mid-run, and in the background or under another `mcmd` when no `sudo -v` ran first. Give the commands
588
+ NOPASSWD. `Defaults noninteractive_auth` (sudo 1.9.10 and later) lets `sudo -n` sign in with no question, but then
589
+ pam_faillock counts each refusal of a password sudo as a failed login; sudo 1.9.9 (Ubuntu 22.04) does both by default.
590
+
563
591
  ## Upgrading to 1.70 from 1.69
564
592
 
565
593
  - Nothing needs doing. `mcmd` is unchanged.
@@ -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.71'
33
33
  __version__ = version
34
- COMMIT_DATE = '2026-11-23'
34
+ COMMIT_DATE = '2026-11-25'
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
@@ -1262,7 +1262,7 @@ def set_sudo(use_sudo):
1262
1262
  Set whether to use sudo for commands
1263
1263
 
1264
1264
  @params:
1265
- use_sudo: Whether to use sudo
1265
+ use_sudo: Whether to use sudo ( on a terminal the commands run as sudo -n: see run_commands )
1266
1266
 
1267
1267
  @returns:
1268
1268
  None
@@ -2522,7 +2522,12 @@ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, ext
2522
2522
  for command in commands:
2523
2523
  formatedCommands.extend(__format_command(command,expand=parse,shell=shell,variables=variables))
2524
2524
  if use_sudo:
2525
- formatedCommands = [[SUDO_PATH] + command for command in formatedCommands]
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]
2526
2531
  env = _check_env(env, 'env', drop_empty=True)
2527
2532
  extra_env = _check_env(extra_env, 'extra_env', allow_none=True)
2528
2533
  pass_fds = _check_pass_fds(pass_fds)
@@ -2540,14 +2545,41 @@ def _build_tasks(commands, parse=False, use_sudo=..., shell=False, env=None, ext
2540
2545
  task._unread = unread
2541
2546
  return tasks, bool(use_sudo)
2542
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)
2567
+
2543
2568
  def _validate_sudo():
2544
2569
  '''
2545
2570
  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.
2571
+ In the terminal's foreground sudo can ask for a password, and what it then remembers for the terminal is what the
2572
+ commands ( sudo -n, in process groups of their own, same session ) run on. In a background process group it could only
2573
+ stop ( or loop, with SIGTTIN ignored ), so there it runs as sudo -n -v, which asks nothing, and its refusal ( stderr )
2574
+ goes nowhere: written to the terminal from a background group under `stty tostop` it stops the whole group ( SIGTTOU )
2575
+ 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 ).
2548
2577
  '''
2549
2578
  try:
2550
- subprocess.run([SUDO_PATH, '-v'])
2579
+ if _terminal() is False:
2580
+ subprocess.run([SUDO_PATH, '-n', '-v'], stderr=subprocess.DEVNULL)
2581
+ else:
2582
+ subprocess.run([SUDO_PATH, '-v'])
2551
2583
  except OSError as e:
2552
2584
  _write_error(f'sudo validation failed: {e}')
2553
2585
 
@@ -2737,7 +2769,8 @@ def run_command(command, timeout=0,max_threads=1,quiet=False,dry_run=False,with_
2737
2769
  return_object: Whether to return the Task object
2738
2770
  wait_for_return: Whether to wait for the return of the command
2739
2771
  sem: The semaphore to use for threading
2740
- use_sudo: Whether to use sudo for commands
2772
+ 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
2741
2774
  raise_error: Whether to raise an error if the command fails
2742
2775
  prefix: Whether to prefix output lines with [#] when commands run at once ( never for one command )
2743
2776
  color: Whether to color output lines ( None: when commands run at once on a terminal without NO_COLOR )
@@ -2793,7 +2826,8 @@ def run_commands(commands, timeout=0,max_threads=1,quiet=False,dry_run=False,wit
2793
2826
  parse: Whether to parse ranged input
2794
2827
  wait_for_return: Whether to wait for the return of the commands
2795
2828
  sem: The semaphore to use for threading
2796
- use_sudo: Whether to use sudo for commands
2829
+ 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
2797
2831
  raise_error: Whether to raise an error if the command fails
2798
2832
  prefix: Whether to prefix output lines with [#], the command's 1-based position, when commands run at once
2799
2833
  color: Whether to color output lines per command ( None: when commands run at once on a terminal without NO_COLOR )
@@ -3187,7 +3221,7 @@ def _run_cli():
3187
3221
  parser.add_argument('-p','--parse', action='store_true',help='Parse ranged input and expand them into multiple commands')
3188
3222
  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
3223
  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')
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 )')
3191
3225
  parser.add_argument('-q','--quiet', action='store_true',help='quiet mode: hide command output ( the summary still shows )')
3192
3226
  parser.add_argument('-n','--dry-run', action='store_true',help='print each command, quoted, instead of running it')
3193
3227
  parser.add_argument('--shell', action='store_true',help='run each command through /bin/sh -c ( pipes, ;, > and globs work )')
@@ -16,6 +16,8 @@ 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
+ # ( no terminal: with one the prefix is sudo -n, see test_sudo.py )
20
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: None)
19
21
  def fail():
20
22
  raise AssertionError('sudo -v must not run in a dry run')
21
23
  monkeypatch.setattr(multiCMD, '_validate_sudo', fail)
@@ -34,6 +34,8 @@ 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
+ # ( no terminal: with one the prefix is sudo -n, see test_sudo.py )
38
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: None)
37
39
  tasks, used = multiCMD._build_tasks(['echo hi'], use_sudo=True, shell=True)
38
40
  assert used is True
39
41
  assert tasks[0].command == ['/usr/bin/sudo', '/bin/sh', '-c', 'echo hi']
@@ -0,0 +1,245 @@
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; 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):
57
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
58
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: where)
59
+ tasks, used = multiCMD._build_tasks([['id', '-u'], 'echo hi'], use_sudo=True)
60
+ assert used is True
61
+ assert [task.command for task in tasks] == [prefix + ['id', '-u'], prefix + ['echo', 'hi']]
62
+ # 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)
64
+ assert tasks[0].command == prefix + ['/bin/sh', '-c', 'echo hi']
65
+ multiCMD.USE_SUDO = True
66
+ tasks, _ = multiCMD._build_tasks(['id'])
67
+ assert tasks[0].command == prefix + ['id']
68
+
69
+
70
+ def test_no_sudo_asks_nothing_of_the_terminal(monkeypatch):
71
+ def fail():
72
+ raise AssertionError('the terminal is looked at only for sudo')
73
+ monkeypatch.setattr(multiCMD, '_terminal', fail)
74
+ tasks, used = multiCMD._build_tasks(['id'])
75
+ assert used is False and tasks[0].command == ['id']
76
+
77
+
78
+ # 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
80
+ @pytest.mark.parametrize('where, argv, kwargs', [(None, ['/usr/bin/sudo', '-v'], {}), (True, ['/usr/bin/sudo', '-v'], {}),
81
+ (False, ['/usr/bin/sudo', '-n', '-v'], {'stderr': subprocess.DEVNULL})])
82
+ def test_sudo_v_asks_only_in_the_terminals_foreground(monkeypatch, where, argv, kwargs):
83
+ calls = []
84
+ 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()
88
+ assert calls == [((argv,), kwargs)]
89
+
90
+
91
+ def test_dry_run_shows_sudo_n_on_a_terminal(monkeypatch, capsys):
92
+ monkeypatch.setattr(multiCMD, 'SUDO_PATH', '/usr/bin/sudo')
93
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: True)
94
+ multiCMD.run_commands([['id']], dry_run=True, use_sudo=True)
95
+ assert capsys.readouterr().out == '/usr/bin/sudo -n id\n'
96
+
97
+
98
+ class _FakeTty:
99
+ '''os.open( '/dev/tty' ) and os.tcgetpgrp() for _terminal(): the descriptor is a real one ( /dev/null ), and closes are counted'''
100
+ def __init__(self, monkeypatch, opens=True, pgrp=None, error=False):
101
+ self.fds, self.closed = [], []
102
+ real_open, real_close = os.open, os.close
103
+ def fake_open(path, flags, *args):
104
+ assert path == '/dev/tty' and flags & os.O_NOCTTY
105
+ if not opens:
106
+ raise OSError(6, 'No such device or address', path)
107
+ fd = real_open(os.devnull, os.O_RDONLY)
108
+ self.fds.append(fd)
109
+ return fd
110
+ def fake_close(fd):
111
+ self.closed.append(fd)
112
+ real_close(fd)
113
+ def fake_tcgetpgrp(fd):
114
+ assert fd in self.fds
115
+ if error:
116
+ raise OSError(25, 'Inappropriate ioctl for device')
117
+ return os.getpgrp() if pgrp is None else pgrp
118
+ monkeypatch.setattr(multiCMD.os, 'open', fake_open)
119
+ monkeypatch.setattr(multiCMD.os, 'close', fake_close)
120
+ monkeypatch.setattr(multiCMD.os, 'tcgetpgrp', fake_tcgetpgrp)
121
+
122
+
123
+ @pytest.mark.skipif(os.name != 'posix', reason='a controlling terminal is POSIX only')
124
+ @pytest.mark.parametrize('opens, pgrp, error, answer', [
125
+ (False, None, False, None),
126
+ (True, None, False, True),
127
+ (True, -1, False, False),
128
+ (True, None, True, False),
129
+ ])
130
+ def test_terminal_answers(monkeypatch, opens, pgrp, error, answer):
131
+ tty = _FakeTty(monkeypatch, opens=opens, pgrp=os.getpgrp() + 1 if pgrp == -1 else pgrp, error=error)
132
+ assert multiCMD._terminal() is answer
133
+ # the descriptor it opened is closed, whatever the answer
134
+ assert tty.closed == tty.fds
135
+
136
+
137
+ def test_terminal_is_none_off_posix(monkeypatch):
138
+ monkeypatch.setattr(multiCMD, '_IS_POSIX', False)
139
+ monkeypatch.setattr(multiCMD.os, 'open', lambda *args: pytest.fail('/dev/tty is not opened off POSIX'))
140
+ assert multiCMD._terminal() is None
141
+
142
+
143
+ # a session leader that takes the pty as its controlling terminal ( TIOCSCTTY ) is in its foreground, and so is a child
144
+ # left in its process group; a child moved to a process group of its own is not; and with no controlling terminal there
145
+ # is none
146
+ _TERMINAL_PROBE = r'''
147
+ import fcntl, os, sys, termios
148
+ sys.path.insert(0, sys.argv[1])
149
+ import multiCMD
150
+ if sys.argv[2] == 'tty':
151
+ fcntl.ioctl(0, termios.TIOCSCTTY, 0)
152
+ print('leader', multiCMD._terminal(), flush=True)
153
+ for name in ('same group', 'own group'):
154
+ pid = os.fork()
155
+ if pid == 0:
156
+ if name == 'own group':
157
+ os.setpgid(0, 0)
158
+ print(name, multiCMD._terminal(), flush=True)
159
+ os._exit(0)
160
+ os.waitpid(pid, 0)
161
+ '''
162
+
163
+
164
+ @pytest.mark.skipif(os.name != 'posix', reason='a controlling terminal is POSIX only')
165
+ @pytest.mark.parametrize('kind, expected', [('tty', 'leader True\nsame group True\nown group False\n'),
166
+ ('none', 'leader None\nsame group None\nown group None\n')])
167
+ def test_terminal_on_a_real_pty(kind, expected):
168
+ import pty
169
+ master, slave = pty.openpty()
170
+ try:
171
+ proc = subprocess.run([sys.executable, '-c', _TERMINAL_PROBE, str(PACKAGE_ROOT), kind], stdin=slave if kind == 'tty' else subprocess.DEVNULL,
172
+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True, universal_newlines=True, timeout=60)
173
+ finally:
174
+ os.close(master)
175
+ os.close(slave)
176
+ assert proc.stderr == ''
177
+ assert proc.stdout == expected
178
+
179
+
180
+ # a program using the library, with `stty tostop` on its terminal and nothing remembered by sudo: sudo's refusal, written to the
181
+ # terminal from a background process group, stopped the group ( SIGTTOU ) and the call waited. The stand-in sudo refuses
182
+ # as sudo does, on stderr. The probe is the terminal's session leader ( in its foreground ); the background run forks a child
183
+ # into a process group of its own, which makes the call and exits 0 when the refusal came back as the command's own
184
+ # stderr. LIMIT: the call takes milliseconds, so a regression waits the whole of it, 10 s, and the stopped group is killed
185
+ _TOSTOP_PROBE = r'''
186
+ import fcntl, os, signal, sys, termios, time
187
+ sys.path.insert(0, sys.argv[1])
188
+ import multiCMD
189
+ multiCMD.SUDO_PATH = sys.argv[3]
190
+ LIMIT = 10
191
+ fcntl.ioctl(0, termios.TIOCSCTTY, 0)
192
+
193
+ def call():
194
+ task = multiCMD.run_command(['id'], quiet=True, use_sudo=True, return_object=True)
195
+ return 0 if (task.returncode, task.stderr) == (1, ['sudo: a password is required']) else 3
196
+
197
+ if sys.argv[2] == 'foreground':
198
+ print('foreground', call(), flush=True)
199
+ sys.exit(0)
200
+ pid = os.fork()
201
+ if pid == 0:
202
+ os.setpgid(0, 0)
203
+ os._exit(call())
204
+ deadline = time.monotonic() + LIMIT
205
+ while time.monotonic() < deadline:
206
+ done, status = os.waitpid(pid, os.WNOHANG)
207
+ if done:
208
+ print('background', os.WEXITSTATUS(status) if os.WIFEXITED(status) else 'signal %d' % os.WTERMSIG(status), flush=True)
209
+ sys.exit(0)
210
+ time.sleep(0.02)
211
+ os.killpg(pid, signal.SIGKILL)
212
+ os.waitpid(pid, 0)
213
+ print('background hung', flush=True)
214
+ '''
215
+
216
+
217
+ @pytest.mark.skipif(os.name != 'posix', reason='a controlling terminal is POSIX only')
218
+ @pytest.mark.parametrize('where', ['foreground', 'background'])
219
+ def test_sudo_validation_does_not_stop_on_a_tostop_terminal(tmp_path, where):
220
+ import pty
221
+ import termios
222
+ sudo = tmp_path / 'sudo'
223
+ sudo.write_text('#!/bin/sh\necho "sudo: a password is required" >&2\nexit 1\n')
224
+ sudo.chmod(0o755)
225
+ master, slave = pty.openpty()
226
+ try:
227
+ attrs = termios.tcgetattr(slave)
228
+ attrs[3] |= termios.TOSTOP
229
+ termios.tcsetattr(slave, termios.TCSANOW, attrs)
230
+ proc = subprocess.run([sys.executable, '-c', _TOSTOP_PROBE, str(PACKAGE_ROOT), where, str(sudo)], stdin=slave,
231
+ stdout=subprocess.PIPE, stderr=slave, start_new_session=True, universal_newlines=True, timeout=60)
232
+ # what the probe wrote to its terminal ( a traceback, sudo's refusal ), for a failure's message
233
+ shown = b''
234
+ while select.select([master], [], [], 0)[0]:
235
+ try:
236
+ data = os.read(master, 4096)
237
+ except OSError:
238
+ break
239
+ if not data:
240
+ break
241
+ shown += data
242
+ finally:
243
+ os.close(master)
244
+ os.close(slave)
245
+ assert proc.stdout == where + ' 0\n', shown
@@ -141,6 +141,8 @@ 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
+ # ( in the terminal's foreground: elsewhere see test_sudo.py )
145
+ monkeypatch.setattr(multiCMD, '_terminal', lambda: True)
144
146
  monkeypatch.setattr(subprocess, 'run', lambda *args, **kwargs: calls.append((args, kwargs)))
145
147
  multiCMD._validate_sudo()
146
148
  assert calls == [((['/usr/bin/sudo', '-v'],), {})]
@@ -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
File without changes
File without changes