1752587 Members
4399 Online
108788 Solutions
New Discussion юеВ

Script to check user id

 
SOLVED
Go to solution
shikhar_1
Regular Advisor

Script to check user id

Hi,

I just to create a script who can run only root user and once any other user(not root) will try to execute, will be getting non-root error.
I believe for that we need to compare user id and in the starting of the script and if it goes corect then script will run.

Appreciating your reponse.
4 REPLIES 4
Manix
Honored Contributor

Re: Script to check user id

Not sure ,what is the exact question .

Are you talking about setting setuid on the script so that the user executing the script gains the permission as the owner has for that file.


What are the current permission on the file.

Thanks
Manix
HP-UX been always lovable - Mani Kalra
Matti_Kurkela
Honored Contributor
Solution

Re: Script to check user id

Do you mean something like this:

-----
#!/bin/sh
if [[ $(whoami) != "root" ]]; then
echo "${0##*/}: Access Denied: you must be root to run this script."
exit 1
fi

# If we get this far, we must be running as root.
# Add whatever you want here.
echo "OK, you're root"
-----

MK
MK
Jose Mosquera
Honored Contributor

Re: Script to check user id

Hi,

First review these "id" command options:
#id -u
Display the effective user ID
-or-
#id -ur
Display the real ID instead of the effective ID

Then you can asign one of them to a variable and ask if the content is "root":

WHOIS=`id -ur`
if [ "$WHOIS" != "root" ]
then
echo "root privileges are requested to run this script"
exit 99
fi

Rgds.
James R. Ferguson
Acclaimed Contributor

Re: Script to check user id

Hi:

I would query the UID of the process with 'id -u'. This will return zero (0) if the 'root' user is the real *or* the effective ID.

If you need to distinguish between the real and the effective UID of a process, add the '-r' option to 'id' as 'id -ur'.

If the real UID and the effective UID aren't the same, the user may have performed an 'su -' operation, or the process may have been 'setuid'.

I prefer to use 'id' as opposed to 'whoami' or 'who am i' since it's the numeric UID of zero that signifies "root" or "superuser" privilege. One could, but should not, have multiple UID=0 accounts in '/etc/passwd' and the name "root" is ambiguous in that case.

Regards!

...JRF...