1

I am aware that I can prevent sudo command while I execute script; Suppose I have one test bash script and I don’t want that someone executes this script by issuing the following command:

username:~#sudo ./test

I implement one of following methods to prevent the above execution, I also implement one die method for that.

if [[ $UID = 0 ]] ; then
  die "Please dont use sudo command with script"
fi

But i am not sure what I'm supposed to implement if root user themselves want to use the script. My above method will prevent root to use that script.

I am ok if root wants to execute script by this manner

root:~#./test

2 Answers 2

2

I think you could check $SUDO_USER

from man page of sudo:

SUDO_USER
Set to the login name of the user who invoked sudo.

a little test:

#!/bin/bash
[[ -z $SUDO_USER ]] && echo "Not from sudo" || echo "You are from sudo"

save it as t.sh then we have:

kent$  ./t.sh
Not from sudo

kent$  su
Password: 

root# ./t.sh
Not from sudo

kent$  sudo ./t.sh
You are from sudo
Sign up to request clarification or add additional context in comments.

Comments

1

There is an answer on serverfault. In essence, there are multiple environment variables set:

SUDO_COMMAND
SUDO_USER
SUDO_UID
SUDO_GID

As noted in the linked post, they can be faked by setting them by hand. It might help you in your case, though.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.