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
  • 8,910
  • 6
  • 33
  • 52
Royce
  • 1,397
  • 2
  • 14
  • 35

1 Answers1

1

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
  • 8,910
  • 6
  • 33
  • 52