How do I run a .sh script with root privileges from Ubuntu's cmd? Some scripts require to enter the password. I watn to avoid this.
5 Answers
If security is a concern, I wouldn't do this as has been mentioned.
Better would be to use visudo to edit the sudoers file, and edit all the commands that the script uses that need to be root. So, the whole script doesn't need to be root, but maybe shutdown does (contrived example), so:
fooUser ALL=(ALL) NOPASSWD:/sbin/reboot,/sbin/shutdown
This means that fooUser will be able to run the reboot and shutdown commands from ALL terminals and when they are acting as any (ALL) user.
And then, in the scipt:
sudo /sbin/shutdown

- 83,619
- 74
- 305
- 448
Do you mean a command inside the script is asking for a password, or that you just want to run it once with a password at launch, or that you have a script that's automated to run and is pausing for a password?
I normally launch with sudo from the command prompt and it uses root privileges, but otherwise you may have to muck with the sudoer's file in /etc to apply "nopasswd" to the command or script you're using.

- 31,172
- 9
- 67
- 87
Edit the sudoers file using the visudo command as follows:
%cdrom ALL = NOPASSWD: /usr/bin/k3b
This is not a good practice for shell scripts unless you are running an application like tripwire that will detect changes to the script.

- 20,797
- 4
- 31
- 39
Asside all the other advice in the answers to your question ... you could also open a bash shell (Terminal) and then type sudo su - , enter your password wich will give you a shell with root privilegs from where you can run scripts as root without re-entering the password.
As other's have advised: be carefull
user@prompt>sudo su -
password: xXxXxXx
root@prompt>

- 920
- 11
- 19
-
That's what I've got: training@training-vm:~$ sudo su - root@training-vm:~# /home/training/myscript.sh root@127.0.0.1's password: I have to reenter the password now – lak-b Aug 03 '09 at 17:27
You can use NOPASSWD
in /etc/sudoers
to not prompt for a password for some/all commands/users/hosts when using sudo
.
See the manpage.

- 3,952
- 1
- 22
- 16
-
There are concerns with saying "all" without explicitly mentioning this is a circumvention of the point of implementing `sudo` functionality to begin with. – Krista K Jan 06 '23 at 17:26