Changing to root user inside shell script

孤者浪人 提交于 2019-11-30 17:20:54
Igor Chubin

sudo will work here but you need to change you script a little bit:

$ cat 1.sh 
id 
sudo -s <<EOF
echo Now i am root
id
echo "yes!"
EOF

$ bash 1.sh
uid=1000(igor) gid=1000(igor) groups=1000(igor),29(audio),44(video),124(fuse)
Now i am root
uid=0(root) gid=0(root) groups=0(root)
yes!

You need to run your command in <<EOF block and give the block to sudo.

If you want, you can use su, of course. But you need to run it using expect/pexpect that will enter password for you.

But even case you could manage to enter the password automatically (or switch it off) this construction would not work:

user-command
su 
root-command

In this case root-command will be executed with user, not with root privileges, because it will be executed after su will be finished (su opens a new shell, not changes uid of the current shell). You can use the same trick here of course:

su -c 'sh -s' <<EOF
# list of root commands
EOF

But now you have the same as with sudo.

There is an easy way to do it without a second script. Just put this at the start of your file:

if [ "$(whoami)" != "root" ]
then
    sudo su -s "$0"
    exit
fi

Then it will automatically run itself as root. Of course, this assumes that you can sudo su without having to provide a password - but that's out of scope of this answer; see one of the other questions about using sudo in shell scripts for how to do that.

Josh

The easiest way to do that would be to create a least two scripts.

The first one should call the second one with root privileges. So every command you execute in the second script would be executed as root.

For example:

runasroot.sh

sudo su-c'./scriptname.sh'

scriptname.sh

apt-get install mysql-server-5.5

or whatever you need.

Juan T

Short version: create a block to enclose all commands to be run as root.

For example, I created a script to run a command from a root subdirectory, the segment goes like this:

sudo su - <<EOF
cd rootSubFolder/subfolder
./commandtoRun
EOF
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!