2

I have a shell script in which most of the commands need to be run under sesu user and then I need to run some commands as current user. Can you please help me in this?

4 Answers 4

1

If you do not want to specify password every time, add sesu to sudoers group and run command you want this way:

sudo su -c "command string"

This way command string runs as superuser (root etc).

1
  • Modify the sudoers file. In some operating systems, a "sudoers" group pre-exists and has some rights. You can authorize users to only run certain commands. An entirely different approach may be to use an SSH key which runs only specific commands. Those approaches can be combined. (Then also use MariusMatutiae's answer as necessary.)
    – TOOGAM
    Mar 3, 2016 at 0:46
1

The command

    exit

closes the current shell. If you were running a shell like user X, then switched to a user Y, exit closes the shell in which you were Y and returns you to being X

0

You can use su to switch to other user and the -c option to execute the command, e.g.

 su anotherUser -c "ls /"

Check if you have sudo and consider if you can use it in your case. The su sample above will ask for the password of anotherUser, and that could be annoying.

0

I have been in a similar situation recently. Here is what I have done to go to superuser level immediately when a script is called, and subsequently perform regular-user tasks. I think it may help you figure a way to get to the desired solution:

#!/bin/bash

# generic_sudo.sh
# Tool that demonstrates in-then-out of sudo
# This demo is pointless if called with 'sudo generic_sudo.sh'

# Need root priviledges for some superuser work
if (( EUID != 0 )); then # If the user is not "root":
# In general one should use ((..)) for testing numbers and integer variables, and [[..]] for testing strings and files.
    sudo $0                         # Relaunch it as "root".
    EXITCODE=$?
    printf "su mode OFF.\n"         # If we got here, we left superuser mode
    printf "EUID is: %d\n" $EUID
    printf "Exit code %d\n" $EXITCODE
    exit $EXITCODE                  # Once it finishes, exit gracefully.
else
  printf "su mode ON.\n"
fi                              # End if.

printf "EUID is: %d\n" $EUID

# Some superuser work

printf "Some superuser work was done.\n"
exit 0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .