codec
codec

Reputation: 8806

How to read a file as a different user

I have a file which can only be ready by user root. In a certain script which is run by user1 I am trying to read the file as follows:

from configparser import ConfigParser
properties="/root/role.properties"
cfg = ConfigParser()

with open(properties, 'r') as rolefp:
     cfg.readfp(rolefp)

This raises and exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: '/root/role.properties'

Same script when run as root works. I want to read this file as root. (sudo). Is there any way that can be done except bash/shell.

Upvotes: 1

Views: 901

Answers (2)

pelya
pelya

Reputation: 4494

Nope! Changing active user account from the code without asking for password would be a security hole, so you cannot do it from regular application.

You either need to run your application under root account, or run sudo/pkexec/gksu from inside your code, with a command to read contents of this file and pass them back to your script.

Either way, you will have a password dialog.

Upvotes: 1

Miro
Miro

Reputation: 112

Here you will need to do that file readable by user who is executing your python script.

If it is safe you can add permission 0644 to this file.

Upvotes: 2

Related Questions