The documentation for os.getuid()
says:
Return the current process’s user id.
And of os.geteuid()
says:
Return the current process’s effective user id.
So what is the difference between user id and effective user id?
For me both works same (on both 2.x and 3.x). I am using it to check if script is being run as root.
To understand how os.getuid
and os.geteuid
differ, you need to understand that they're are not Python specific functions (other than the os
module prefix). Those functions are wrapping the getuid
and geteuid
system calls that are provided by essentially all Unix-like operating systems.
So, rather than looking at Python docs (which are not likely to give a lot of details), you should look at the docs for your operating system. Here is the relevant documentation for Linux, for example. Wikipedia also has a good article on Unix User IDs.
The difference between the regular UID and the Effective UID is that only the EUID is checked when you do something that requires special access (such as reading or writing a file, or making certain system calls). The UID indicates the actual user who is performing the action, but it is (usually) not considered when examining permissions. In normal programs they will be the same. Some programs change their EUID to add or subtract from the actions they are allowed to take. A smaller number also change their UID, to effectively "become" another user.
Here's an example a program that changes its EUID: The passwd
program (which is used to change your password) must write to the system's password file, which is owned by the root user. Regular users can't write to that file, since if they could, they could change everyone else's password too. To resolve this, the passwd
program has a bit set in its file permissions (known as the setuid bit
) that indicates to the OS that it should be run with the EUID of the program's owner (e.g. root
) even when it is launched by another user. The passwd
program would then see its UID
as the launching user, and its EUID as root. Writing to the system password file requires the EUID to be privileged. The UID is useful too, since passwd
needs to know which user it's changing the password for.
There are a few other cases where the UID and EUID won't match, but they're not too common. For instance, a file server running as the super user might change its EUID to match a specific user who is requesting some file manipulations. Using the user's EUID allows the server to avoid accessing things that the user is not allowed to touch.