How to enter password only once in a bash script needing sudo
Data
- I want operator users on this machine to mount their own cifs shares
- The
sudoers
file already contains the/bin/mount -t cifs //*/* /media/* -o username=*
command for all operators - I want the users to mount a
cifs
share through a script typing the password only once, not twice. - The sudo password and the cifs password are identical.
What I already have
This script works:
#!/bin/bash
sudo 'mount -t cifs //192.168.1.1/home /media/$USER/home -o username=$USER'
...but it requires the users to type the same password twice!
- Once for
sudo
- Once for the mount itself
This would also work:
#!/bin/bash
echo -n Password:
read -s szPassword
echo $szPassword | sudo -S sh -c 'echo $szPassword | mount -t cifs //192.168.1.1/home /media/$USER/home -o username=$USER'
...but this would require me to allow all operator users to be able to sudo sh
(major security problem)
Question
How to mount a cifs share in bash¹ without putting sh
in the sudoers
file nor creating a permanent/temporary file???
Note 1: no python, perl, C, Go, ... please?
Note 2: I know I can just remove the password through the sudoers
file, but I'm trying to tighten security, not loosen it, without giving up convenience...
Solution 1:
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.
Solution 2:
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:
- Doesn't create any files containing passwords
- Allows the user to type only one password for multiple shares (including Windows ones)
- Has no need for extra privileges to be granted. :-)