Welcome, guest | Sign In | My Account | Store | Cart

You don't want that a user can run a particular script, just add this two lines at the beginning of your code.

Python, 5 lines
1
2
3
4
5
import os, sys

# if not root...kick out
if not os.geteuid()==0:
    sys.exit("\nOnly root can run this script\n")

This recipe show how simple is to avoid any access from user to your scripts. You can add this lines at the beginning and the script won't start, but you can also put it in a particular class or function to deny only that part of the script. In addition remember to protect your file, owned by root and chmod 700.

4 comments

Corey Wright 17 years, 3 months ago  # | flag

not a security measure. may i suggest you deemphasize the "chown root may i suggest you deemphasize the "chown root

Corey Wright 17 years, 3 months ago  # | flag

let's try again, dang it. may i suggest you deemphasize the "chown root; chmod 700" which removes the need for your recipe.

chown and chmod are real security measures. checking if a user is root is a courtesy. please don't confuse recipe users about the two.

if a script is owned by root and only accessible to root, there's no reason to check the uid of the executing user. and if the user can read the script, they can always copy it elsewhere, remove the uid check, and run the script. and then there's always debian's fakeroot which allows a user to execute an application impostering to the application (but not the operating system) as root.

i frequently see uid checks imployed within debian init scripts to avoid a user from starting a service which can partially run as non-root (writing temporary files, binding to a port greater than 1024), but in some way fail (unable to read privileged files), leaving the service started but in a broken state. i appreciate these checks when i stupidly try to run an init script from my normal user account, having forgotten to "su" or "sudo" first.

thanks for showing a python implementation of what is commonly done in shell, as i'm familiar with the shell, but still learning how to do similar things in python.

ps what's up with all the random comments from other recent python recipes (irc and tar)?

Gian Mario Tagliaretti (author) 17 years, 2 months ago  # | flag

explanation. chown and chmod don't removes the need for this recipe, imho.

if your script is readable by everyone they can just copy and paste in a new file for example and "maybe" do something they are not suppose to do....

As sysadmin I've learned not to trust 100% users.... :)

Anyway thanks for your comment, they are always appreciated.

Andy Balinsky 16 years, 4 months ago  # | flag

Checking For Root Can Still Be Useful. Checking for root can still be useful if, for example, you want to check whether a user has the privilege to bind a socket to a port less than 1024. In this case, you can generate a useful error message beforehand, rather than just trying and having the bind command fail.