开发者

How to run a script with root authority in Linux

开发者 https://www.devze.com 2023-03-08 16:19 出处:网络
I have to develop a Web site written in CGI. I would like to know how to run a script with root authority开发者_StackOverflow中文版 from CGI.

I have to develop a Web site written in CGI.

I would like to know how to run a script with root authority开发者_StackOverflow中文版 from CGI.

Let's say the script name is hello, I run it from CGI like system("pathToTheFile/hello").

Now I would like to run this hello file as root; can anybody help me with this?


Generally the safest way to do this kind of thing is to use the setuid feature of UNIX-like OSs. If you set the owner of the hello program to be root, and then set the setuid bit:

chmod u+s hello

Then no matter who executes the program, it will execute as root. This works for native executables, but not for interpreted scripts. If "hello" has to be a script, then this won't work for you.

Now, I have to say that in general, setuid root programs aren't a great idea. Often you can create a special user to own the script, and give that user some limited privileges needed, and then make the script setuid to that user.


A much safer method of doing things as root from a web page is to disconnect the program execution from the web page. Instead, use Unix local sockets, named pipes, or a directory of queued jobs.

The directory is probably the easiest to handle. Set up a directory that your web page can write files into. When your page needs something done, write a file describing the job. Then you have a program running as root waiting for new jobs. It can run continuously if it needs fast response or it can run every minute or every few minutes using a crontab entry.


The normal method would be to have the executable file owned by the user you want to run it as, then set the SUID bit.

The method of using sudo usually requires user input for the password (there are ways around this but they're hideously complex).

I suppose I don't need to mention that setting the SUID bit is a very dangerous thing to do, yes? If there's any other way to do what you want, you should use it.


One thing you may want to consider is to pose the question not in terms of the solution you need but in terms of the problem you want solved. Running as root is a solution and not necessarily a good one. Post what you're trying to achieve rather than how, and we can help you out in a far less dangerous way.

0

精彩评论

暂无评论...
验证码 换一张
取 消