Search code examples
zshsudomacos-big-suriterm

sudo asks for a password instead of getting it from stdin


I have a script running in an open terminal window:

while sleep 345600; \
  do pass="$(security find-generic-password -w -s 'service' -a 'account')"; \
     sudo --stdin <<< "${pass}" head /etc/hosts; \
done

When for a test I manually run this script having set sleep to 1, it works as intended, sudo getting the pass without user's interaction. When I then run the script with the 4 days delay, it does not run the same say in a specified time, sudo waiting for the password from a user's terminal (i.e. typed manually!). I can even set the pass variable to contain the actual plain-text password, of no avail.

Why this difference?


Solution

  • It's probably safer to add the particular command you need to the sudoers config and allow it to be run without a password (see https://apple.stackexchange.com/q/398656 for an example of this on macOS).

    If that's not an option, you can try using the --askpass option: it takes the path to a command that will output the user's password on stdout when called. Put the find-generic-password command in a helper script and pass that to --askpass.