Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, check if executed as root

How can I check if my program is running with root permission. Does Pathlib offer the possibility to query the USER-ID under Linux


2 Answers

You can access username with standard library package getpass:

import getpass
print(getpass.getuser())

When code is executed with sudo or as root, the user is the string root.

like image 109
Lesnek Avatar answered Jun 21 '26 05:06

Lesnek


Use os.geteuid() to check if the effective UID is zero.

import os

if os.geteuid() == 0:
    print("Running as root")

getpass.getuser() is not a reliable solution for a few reasons:

  • There can be multiple usernames that map to the superusder userid. If the user logs in with a username other than root the check will fail.
  • It uses environment variables by default, which can be manipulated by the user.
  • If the code is being run from a set-uid process, its permissions may not match the login username.
like image 32
Barmar Avatar answered Jun 21 '26 06:06

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!