The -A
sudo option allows you to specify a helper program (in the SUDO_ASKPASS variable) that will ask for the password.
Create a script to ask the password (myaskpass.sh):
#!/bin/bash
zenity --password --title=Authentication
Then insert this line at the beginning of your script:
export SUDO_ASKPASS="/path/to/myaskpass.sh"
and replace all occurences of sudo <command>
with:
sudo -A <command>
You can use whatever password asking program you want instead of zenity
. I had to encapsulate it within a script because SUDO_ASKPASS must point to a file, so it won't work with the --password
option required by zenity
.
The above works like a charm if it runs from command line or if you choose Run in terminal after double click the script file in the file manager, but if you choose Run or try to launch it from a .desktop file every sudo
will ask for the for password again.
If you don't want a terminal window at all, you can store the password in a variable and pipe it to sudo -S
. Maybe there's some security concerns, but I think it's pretty safe (read the comments on this answer).
Insert this line at the beginning of your script:
PASSWD="$(zenity --password --title=Authentication)\n"
and replace all occurences of sudo <command>
with:
echo -e $PASSWD | sudo -S <command>
To elevate privileges for few commands in script use sudo with heredoc syntax:
possiblevariable=something
sudo /bin/bash <<EOF
cd /somedir
pwd
commandasroot1 "$possiblevariable"
commandasroot2
EOF
nonrootcommand (and not in /somedir)
Testing cd: (working dir changed inside heredoc, but restores as it be before at end of heredoc)
leonid@DevSSD:~$ sudo bash <<EOF
> cd /tmp
> pwd
> EOF
[sudo] password for leonid:
/tmp
leonid@DevSSD:~$
One more example, shows how variables substitution work in heredoc:
leonid@DevSSD:~$ sudo bash <<EOF
cd /tmp
echo $PWD; echo \$PWD
EOF
[sudo] password for leonid:
/home/leonid
/tmp
leonid@DevSSD:~$
Update: example how you can get output into variable
leonid@DevSSD:~$ variable=$(sudo bash <<EOF
cd /tmp
echo $PWD; echo \$PWD
EOF
)
[sudo] password for leonid:
leonid@DevSSD:~$ echo $variable
/home/leonid /tmp
Best Answer
The best solution would be use
visudo
(this tool was made for that and will avoid the exposition of root password), I suggest you to dig what are going wrong with that.As a workaround, you can run this:
(start the command with a space so it won't be saved in bash history).
Regards.