I have a script which can run as sudo script.sh
or pkexec script.sh
It would be much nicer from the user point of view if the script asked for the password from the user when just running it by name script.sh
.
How can I "embed" request to pkexec
or sudo
to run the whole script with root privilege?
Note that running everything with sudo sh -c
might not be the best solution as I have functions in the script.
This'll work:
example:
blade19899's answer is indeed the way to go, however one could also call
sudo bash
in the shebang:The obvious caveat is this will work only as long as the script is called with
./script
and will fail as soon as the script is called withbash script
.If you'd like a pretty dialog, try something like this. I ripped this straight out of something else I wrote, so it's got extra stuff you might not need or want, but it shows the general idea:
This uses whiptail, which you can install if you don't already have it:
I preface the commands within the script which need root access with
sudo
- if the user has not already gained permissions, the script prompts for a password at that point.example
This script can either be run as
sudo <scriptname>
or as<scriptname>
. In either case it will ask for the password, only once.It appears that nobody else has addressed the obvious concern here. Putting
sudo
within your script that you then distribute promotes bad user habits. (I'm assuming you're distributing it because you mention "from a user point of view.")The truth is that there is a guideline in using applications and scripts which is similar to the security principle in banking of: Never give out your personal information to someone who calls you and says they're calling "from your bank", and which exists for similar reasons.
The rule for applications is:
Never type in your password when prompted unless you are certain what is being done with it. This applies triply to anyone with
sudo
access.If you're typing your password in because you ran
sudo
on the command line, great. If you're typing it in because you ran an SSH command, fine. If you're typing it in when you log in to your computer, great, of course.If you just run a foreign script or executable and tamely enter your password when prompted for it, you have no idea what the script is doing with it. It could be storing it in a temp file in plaintext, for all you know, and might even fail to clean up after itself.
Obviously there are separate and additional concerns about running an unknown set of commands as
root
, but what I'm talking about here is maintaining security on the password itself. Even assuming the application/script is not malicious, you still want your password to be handled securely to prevent other applications from getting hold of it and using it maliciously.So, my own personal response to this is, the best thing to put in your script if it needs root privileges, is:
I did it this way: