1

Suppose I am writing a shell script that requires root privileges to run, for example-

#!/bin/sh
ip -s -s neigh flush all
ufw enable

How can I prevent certain lines of code to be run as root, i.e. suppose I add a line in the above script which starts the TOR browser .

#!/bin/sh
ip -s -s neigh flush all
ufw enable
sh -c '"/home/back/Downloads/tor-browser_en-US/Browser/start-tor-browser" --detach || ([ !  -x "/home/back/Downloads/tor-browser_en-US/Browser/start-tor-browser" ] && "$(dirname "$*")"/Browser/start-tor-browser --detach)' dummy %k

As TOR always run in non root mode, what changes should I make in the above script to allow execution of tor as non-root user and rest of the script as root user ?

2

Using sudo:

#!/bin/sh
ip -s -s neigh flush all
ufw enable
sudo -Hu username sh -c '"/home/back/Downloads/tor-browser_en-US/Browser/start-tor-browser" --detach || ([ !  -x "/home/back/Downloads/tor-browser_en-US/Browser/start-tor-browser" ] && "$(dirname "$*")"/Browser/start-tor-browser --detach)' dummy %k
  • -H: Sets the $HOME environment variable to the target user's home directory
  • -u: Runs the command as the specified target user instead of as root
  • username: Argument to -u; specifies the target user's username
1

There are two ways to go about this.

1) Run the script as a non-root user and use sudo to raise privileges to the root user (prefix the commands to be ran as root with sudo).

or

2) Run the script as root user and use su to run the tor command as non-root user. su allows you to stipulate what user to run the command as and the -c option to specify what commands to run. I would also suggest putting the "tor" command in a script itself if calling it via su.

  • second method didnt work for me. Thanks for the answer though – Backspace Jun 18 '15 at 8:16
  • Did you put the tor command line into a script before calling it with su? – Drav Sloan Jun 18 '15 at 9:49
  • su only works if he target user has a login shell that's actually a shell, which isn't always the case for system users. – Gilles Jun 18 '15 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.