shell script- How can I use gksudo to perform consecutive sudo operations with only one password prompt?

StackOverflow https://stackoverflow.com/questions/10470084

  •  06-06-2021
  •  | 
  •  

Question

I want to use sudo to mount two separate network drives on an ad-hoc basis as my NAS device is not always on line, so I am not convinced that adding anything to /etc/fstab is necessary.

The following code is able to achieve this, however I do not intend to run the script from a terminal, thus the sudo password prompt is my issue:

#!/bin/sh

sudo mount -t cifs //10.1.1.9/Volume_1 /media/DNS323-A -ousername=user,password=pass,iocharset=utf8
sudo mount -t cifs //10.1.1.9/Volume_2 /media/DNS323-B -ousername=user,password=pass,iocharset=utf8

I need to select "run in terminal" to be able to successfully run that script from a file browser window. Thus I would prefer to use gksudo, which will open a prompt window for me to enter the sudo password.

However, if I instead use the following code I have to type the sudo password twice!

gksudo "mount -t cifs //10.1.1.9/Volume_1 /media/DNS323-A -ousername=user,password=pass,iocharset=utf8"
gksudo "mount -t cifs //10.1.1.9/Volume_2 /media/DNS323-B -ousername=user,password=pass,iocharset=utf8"

At this point I tried to be smart and use the gksudo option to "run as sudo" as follows, however only the first drive is mounted like the first script above would fail silently if not run from a terminal:

gksudo -S "mount -t cifs //10.1.1.9/Volume_1 /media/DNS323-A -ousername=user,password=pass,iocharset=utf8"
sudo "mount -t cifs //10.1.1.9/Volume_2 /media/DNS323-B -ousername=user,password=pass,iocharset=utf8"

What I'd really like to be able to do is the following, but I'm not sure if it's possible:

gksudo this{
command1
command2
command3
}

Is it just me or does gksudo have a short memory?

Was it helpful?

Solution

this is a script, so the best way would be not to have the sudo/gksudo commands in the script, but call the script using sudo.

I don't think gksudo has any memory itself, that's all sudos doing which is being used in the background.

another possiblitiy would be to use:

gksudo "sh -c 'command1; command2; ...'"

but that's not very elegant.

OTHER TIPS

I use this pretty frequently to ensure users run my scripts as "root" -- recalling from memory, so I may have a couple things turned around.

#!/usr/bin/env

main() {
    # Code to be executed
}

if [[ "$0" == "${BASH_SOURCE[0]}" ]]; then
    [[ $EUID != 0 ]] && exec sudo "$0" $*
    main $*
fi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top