Changing to root user inside shell script

后端 未结 5 1373
不思量自难忘°
不思量自难忘° 2021-01-03 21:13

I have a shell script which needs non-root user account to run certain commands and then change the user to root to run the rest of the script. I am using SUSE11. I have use

5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-03 21:52

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

    $ cat 1.sh 
    id 
    sudo -s <

    You need to run your command in < 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' <

    But now you have the same as with sudo.

提交回复
热议问题