0

How to know if a script has been start with root rights?

At the beginning I would to do something like this :

import ...

print('Welcome')

if_start_with_sudo:
    ...
else:
    print('This program must be start as root')
    exit()

It is possible?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Royce
  • 1,557
  • 5
  • 19
  • 44

1 Answers1

3

Use Python os module's geteuid(). According to its documentation:

Return the current process’s effective user id.

Considering that the root user's UID is always 0, you just need to check if os.geteuid() returns 0:

if os.geteuid() == 0:
    # UID is 0, your program is being run by the root user
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56