How to enter password only once in a bash script needing sudo

You should instead make the user do the call of using sudo as sudo script. just check if the script is being run as root, if not ask for it

if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root, use sudo "$0" instead" 1>&2
   exit 1
fi

Don't try to capture the password of your users.


I'm dumb!

The following script:

#!/bin/bash
read -p "Password: " -s szPassword
printf "%s\n" "$szPassword" | sudo --stdin mount -t cifs //192.168.1.1/home /media/$USER/home -o username=$USER,password="$szPassword"

just works and:

  1. Doesn't create any files containing passwords
  2. Allows the user to type only one password for multiple shares (including Windows ones)
  3. Has no need for extra privileges to be granted. :-)

Require no sudo password for executing this command; the password prompt for mount remains.

In sudoers, include something like

ALL        ALL = NOPASSWD: /bin/mount -t cifs //*/* /media/* -o username=*

After including this, sudo will no longer ask for a password for this specific command; the user still needs to provide a password to the mount command.

Note: I took the command verbatim from what you included in the question; I didn't check whether its wildcards would allow for users to do something nasty. Read the sudoers manpage for examples of nastiness. In particular, note that this line in sudoers allows the user to add any number of -o switches or other arguments to mount. You may want to rethink your approach, e.g. by adding a script such as @Braiam proposes and allow running that through sudo without extra authentication. The script then ensures that users can only run the specific form of mount that you want them to run.

Also, instead of allowing this for all users, you could also limit this to members of a certain group, e.g. you could create a group cifsmount and then have

%cifsmount ALL = NOPASSWD: /bin/mount -t cifs //*/* /media/* -o username=*

Tags:

Bash

Sudo

Scripts