开发者

How do I run a shell script as root (sudo)?

I have a SVN repository server that runs under the repository user. I want to run a script after every post-commit action. I wrote a shell script that runs from the hook after every commit. It needs to be run as root. This is why I used sudo in the script, but it didn't work. Is there any way to run the script as root?

sudo su
echo "password"
svn export --force file:///home/repository/trunk/ /home/memarexweb/public_html/devel/
chmod -R 777 /home/memarexweb/public_htm开发者_JAVA技巧l/devel/


I was searching around and found this useful solution:

Edit your sudoers file to allow running certain commands without a password.

It's best to split your post-commit script into two parts, one of which will be run through sudo.

  • entry in /etc/sudoers:

    loqman    ALL=(root) NOPASSWD: /usr/local/bin/svn-postcommit-export
    
  • Your post-commit hook:

    #!/bin/sh
    sudo /usr/local/bin/svn-postcommit-export
    
  • Script /usr/local/bin/svn-postcommit-export:

    #!/bin/sh
    svn export --force file:///home/repository/trunk/ /home/memarexweb/public_html/devel/
    chmod -R 777 /home/memarexweb/public_html/devel/
    

    (You can choose any name and put the script anywhere; I just suggested svn-postcommit-export as an example, and /usr/local/bin as a common location.)


sudo su

starts a new process, owned by the root user. After that process is terminated or stopped, the next line is executed, again as the user that executes the script.

A possible solution is to run the whole script using sudo, and to give that use sudo rights to exectute the scripts. In order to do that, you need to edit the /etc/sudoers file using the visudo command.


Run a script as root:

sudo sh your-script.sh


In the last line of your script, you're changing the mode of /home/memarexweb/public_html/devel/ to 777, so user "repository" should be able to copy files to that directory without root privileges. In that case, you don't need to use sudo or su.

However, changing the permissions of the directory to 777 is dangerous, as it allows anyone to write to that directory and create or delete files. It would be better to change the ownership of the directory to user "repository" and change the mode to 755. If that's not feasible, you may be able to add a POSIX ACL allowing "repository" to write to the directory. You can Google "POSIX ACL" for more information, or read the man pages for getfacl and setfacl.


This will not work, the best thing is to put only the requires commands in the shell script. And then setuid the script itself, like this (using root):

chmod u+s myscript.sh

Like this, executing this script will give you the permissions of the owner of the script (root).

EDIT: As mentioned in comments, stuid is not allowed for shell script. This solution works for executable files only.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜