Stop Being Root in the Middle of a Script That Was Run with Sudo

Stop being root in the middle of a script that was run with sudo

In a script run by sudo, use:

su -c "shell command; shell command" $SUDO_USER 

within that script to execute commands as the normal user who invoked sudo.

This works because sudo sets the environment variable SUDO_USER to the original username.

If you have a bunch of commands to run as the original user, you could use a hereis document.

Here is an example script file as proof of concept:

myscript.sh

#!/bin/bash
echo "Part 1"
echo "now running as:"
whoami
echo "SUDO_USER is:"
echo $SUDO_USER
su $SUDO_USER <<EOF
echo "Part 2"
echo "now running as:"
whoami
echo "SUDO_USER is:"
env | grep ^SUDO_USER
sleep 5
EOF
echo "Part 3"
echo "now running as:"
whoami
echo "SUDO_USER is:"
echo $SUDO_USER

And here's the output on sudo ./myscript.sh

Part 1
now running as:
root
SUDO_USER is:
paul
Part 2
now running as:
paul
SUDO_USER is:
SUDO_USER=paul
Part 3
now running as:
root
SUDO_USER is:
paul

Warning: This technique doesn't work so well with nested sudo. If sudo is nested twice, e.g.

sudo su

echo $SUDO_USER
---> me

sudo su
echo $SUDO_USER
---> root

SUDO_USER will return root, not the original username. su $SUDO_USER would then keep running as root. Be careful to avoid that scenario, and it should work ok.

how to terminate a process which is run with sudo? Ctrl+C do it, but not kill

Try the -Z option to tcpdump. It instructs tcpdump to drop root privileges and run as the user specified in the argument.

sudo tcpdump -Z $USER -ieth1 -w ~/dump.bin

Now try killing that process.

Bash script - change to root then exit root

In order to perform the umount as root, use

sudo umount /home/user/myMount

Can I run 'su' in the middle of a bash script?

You can, but bash won't run the subsequent commands as postgres. Instead, do:

su postgres -c 'dropdb $user'

The -c flag runs a command as the user (see man su).

Calling sudo from a script on user login

You might be able to try gksudo. I don't know if gksudo requires a terminal or not, but using gksudo would be cleaner than obtaining input through yad and manually feeding it to sudo. It should also take the same command line arguments

Why can't I use 'sudo su' within a shell script? How to make a shell script run with sudo automatically

Command sudo su starts an interactive root shell, but it will not convert the current shell into a root one.

The idiom to do what you want is something along the lines of this (thanks to @CharlesDuffy for the extra carefulness):

#check for root
UID=$(id -u)
if [ x$UID != x0 ]
then
#Beware of how you compose the command
printf -v cmd_str '%q ' "$0" "$@"
exec sudo su -c "$cmd_str"
fi

#I am root
mkdir /opt/D3GO/
#and the rest of your commands

The idea is to check whether the current user is root, and if not, re-run the same command with su



Related Topics



Leave a reply



Submit