Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
501 views
in Technique[技术] by (71.8m points)

linux - Use sudo without password INSIDE a script

For some reason I need, as user, to run without sudo a script script.sh which needs root privileges to work.
I saw as the only solution to put sudo INSIDE script.sh. Let's take an example :

script.sh :

#!/bin/sh
sudo apt-get update

Of course, if I execute this script, I get a prompt asking me for a password. Then I added to my sudoers file (at the end to override everything else) :

user ALL=(ALL:ALL) NOPASSWD:/path/to/script.sh

By the way, I also tried the line :

user ALL=(ALL) NOPASSWD:/path/to/script.sh

(I think I didn't fully understand the difference)

But this doesn't solve my problem if I don't use sudo to execute this script :

# ./script.sh
[sudo] password for user: 
# sudo ./script.sh
Starts updating...

Well, so I say to myself "Ok, that means that if I have a file refered in sudoers as I did, it will work without prompt only if I call him with sudo, what is not what I want".
So, ok, I create another script script2.sh as following :

script2.sh

#!/bin/sh
sudo /path/to/script.sh

In fact it works. But I am not truly satisfied of this solution, particularly by the fact that I have to use 2 scripts for every command.

This post is then for helping people having this problem and searching for the same solution (I didn't find a good post on it), and perhaps have better solutions coming from you guys.

Feel free to share your ideas !


EDIT 1 :

I want to insist on the fact that this "apt-get update" was just an example FAR from whhat my script actually is. My script has a lot of commands (with some cd to root-access-only config files), and the solution can't be "Well, just do it directly with apt-get".

The principle of an example is to help the understanding, not to be excuse to simplify the answer of the general problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From my blog: IDMRockstar.com:

The kicker is that sometimes, I need to run commands as root. Here's the quick and dirty way I accomplish that without divulging the passwords:

#! /bin/bash
read -s -p "Enter Password for sudo: " sudoPW
echo $sudoPW | sudo -S yum update

This way the user is prompted for the password (and hidden from terminal) and then passed into commands as needed, so I'm not running the entire script as root =)

If you have a better, way, I'd love to hear it! I'm not a shell scripting expert by any means.

Cheers!

.: Adam


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...